首页,制作子弹的预制体,叫:Bullet。
Bullet预制体,添加Componet ---> Rigidbody,取消Use Gravity的勾选。取消重力。
Bullet预制体,带上一个脚本Bullet.cs。
public class Bullet : MonoBehaviour {
Vector3 fwd;
// Use this for initialization
void Start () {
fwd = transform.InverseTransformDirection (Vector3.forward);
}
// Update is called once per frame
void Update () {
GetComponent<Rigidbody> ().AddForce (fwd * 100);//给物体一个向前的力
}
}
然后,制作坦克的主体,随便拉一个Cube好了,改名为Tank。
Tank,带上一个脚本Tank.cs。
public class Tank : MonoBehaviour {
private GameObject goBullet;
private GameObject bullet;
// Use this for initialization
void Start () {
goBullet = Resources.Load ("Bullet") as GameObject;//Bullet预制体要存在在Assets/Resources目录下才能够加载
}
// Update is called once per frame
void Update () {
if (Input.GetButtonDown ("Fire1")) {//按下鼠标左键发射子弹
bullet = Instantiate (goBullet);//将预制体生成对象
bullet.transform.parent = this.transform;//将生成的对象挂在父体上,即子弹挂在坦克上
}
}
}
或者
public class Tank : MonoBehaviour {
public GameObject goBullet;//直接公开预制体的对象框,在界面视图上拉入资源即可。
private GameObject bullet;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetButtonDown ("Fire1")) {//按下鼠标左键发射子弹
bullet = Instantiate (goBullet);//将预制体生成对象
bullet.transform.parent = this.transform;//将生成的对象挂在父体上,即子弹挂在坦克上
}
}
}
网友评论