美文网首页
Unity 坦克发射子弹(简单)

Unity 坦克发射子弹(简单)

作者: 木子才 | 来源:发表于2017-05-19 14:10 被阅读0次

首页,制作子弹的预制体,叫: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;//将生成的对象挂在父体上,即子弹挂在坦克上
        }
    }
}

相关文章

网友评论

      本文标题:Unity 坦克发射子弹(简单)

      本文链接:https://www.haomeiwen.com/subject/uojyxxtx.html