demo@[TOC](unity3d 小白 沙漠坦克)
沙漠坦克是一款双人对战游戏
涉及的一些技术知识点有:
1.将两个游戏物体放在摄像机的范围内
void Start()
{
offset = transform.position - (player1.position + player2.position) / 2; // 获取偏移量
cameras = this.GetComponent<Camera>();
}
// Update is called once per frame
void Update()
{
if (player2 == null || player1 == null) return;
// 设置相机的位置
transform.position = (player1.position + player2.position) / 2 + offset; // 设置camera位置
float distance = Vector3.Distance(player1.position, player2.position);
if (distance <= 0.5f) return;
//设置相机的视野
float size = distance * 0.875f;
cameras.orthographicSize = size;
}
2.碰撞检测
private void OnTriggerEnter(Collider other)
{
AudioSource.PlayClipAtPoint(shellExplorAudio, transform.position);
GameObject.Instantiate(shellExpPrefab, transform.position, transform.rotation);
GameObject.Destroy(this.gameObject);
if(other.tag == "Tank")
{
other.SendMessage("TankDamage");
}
}
3.使用sendMessage 在游戏对象之间发送消息的函数。通过SendMessage函数,可以在游戏对象之间调用方法,从而实现脚本之间的通信。SendMessage方法可以用于调用任何公共方法,不仅限于MonoBehaviour脚本中的方法。
other.SendMessage(“TankDamage”);
public void TankDamage()
{
if(hp <= 0)
{
return;
}
hp -= Random.Range(10, 20);
hpslider.value = (float)hp / hpTotal;
if(hp <= 0) // 血量未0是控制死亡效果
{
AudioSource.PlayClipAtPoint(tankDieAudio, transform.position);
GameObject.Instantiate(tankExpolsion, transform.position + Vector3.up, transform.rotation);
GameObject.Destroy(this.gameObject);
}
}
当子弹和对方发生碰撞时通过sendMessage方法让坦克设置自己的血量
4.由于是两个玩家,需要设置不同的输入按钮
Edit->ProjectSettting 搜索 input
通过不同的设置不同玩家的操作按钮类型