教程:炮塔和子弹
一座炮塔,转向玩家,大约每秒射击一次,只在没有东西挡住时开火。然后再做一种更好的子弹,作为可重复使用的预制体。
1. 炮塔

把脚本放在炮塔的头上(底座上的一个球或方块)。
Scripts/Turret.cs
using System.Collections;
public class Turret : Behaviour
{
public float range = 20f;
public float secondsBetweenShots = 1.2f;
public float shotSpeed = 18f;
GameObject player;
float wait;
public override void Start() { player = GameObject.FindPlayer(); }
public override void Update(float deltaTime)
{
if (player == null) return;
Vector3 aim = player.transform.position + Vector3.up;
if (Vector3.Distance(transform.position, aim) > range) return;
transform.LookAt(aim);
wait -= deltaTime;
// a wall between the two stops the shot (the player themselves does not)
bool blocked = Physics.Linecast(transform.position, aim, out RaycastHit hit, Physics.DefaultRaycastLayers, gameObject) && hit.gameObject != player;
if (wait <= 0f && !blocked)
{
wait = secondsBetweenShots;
StartCoroutine(Shoot());
}
}
IEnumerator Shoot()
{
GameObject ball = GameObject.Spawn("Sphere", transform.position + transform.forward, Vector3.zero, new Vector3(0.3f, 0.3f, 0.3f));
ball.SetColor(Color.red);
ball.AddRigidbody(0.5f);
ball.rigidbody.velocity = transform.forward * shotSpeed;
Audio.PlayAt("Audio/shot.wav", transform.position);
yield return new WaitForSeconds(4f);
if (ball.exists) GameObject.Destroy(ball);
}
}
保存为 Scripts/Turret.cs。
工作原理:transform.LookAt 转动炮头;Physics.Linecast 检查有没有墙挡住射击;StartCoroutine(Shoot()) 启动一个协程,生成一个球,用 velocity 把它射出,四秒后销毁它(yield return new WaitForSeconds)。在 Inspector 中调整 range、secondsBetweenShots 和 shotSpeed。
2. 更好的子弹

刚体小球速度很快时可能穿过薄墙。这种子弹每帧检查自己走过的路径:
Scripts/Bullet.cs
public class Bullet : Behaviour
{
public float speed = 60f;
public float damage = 25f;
public float lifeSeconds = 3f;
float age;
public override void Update(float deltaTime)
{
Vector3 from = transform.position;
Vector3 to = from + transform.forward * speed * deltaTime;
// the whole step of this frame is checked, not only where the bullet ends up: at 60 m/s a frame's step is a metre
if (Physics.Linecast(from, to, out RaycastHit hit, Physics.DefaultRaycastLayers, gameObject))
{
hit.gameObject.SendMessage("TakeDamage", damage);
if (hit.gameObject.rigidbody.exists) hit.gameObject.rigidbody.AddImpulse(transform.forward * 2f);
GameObject.Destroy(gameObject);
return;
}
transform.position = to;
age += deltaTime;
if (age > lifeSeconds) GameObject.Destroy(gameObject);
}
}
把它放在一个小球上,再把小球拖进 Project 面板保存为预制体。枪用下面的代码生成一发子弹:
GameObject shot = GameObject.Instantiate("Prefabs/Bullet.prefab", muzzle);
shot.transform.rotation = transform.rotation;
子弹用与生命值中相同的 TakeDamage 消息伤害路上的第一个东西,所以炮塔、爆炸桶和守卫的反应都一样。
下一步:爆炸桶。