我的Unity(7)一点一滴 从相机向砖墙发射子弹

来源:互联网 发布:网络剧错爱一生演员表 编辑:程序博客网 时间:2024/04/29 06:35

突发想写这个代码,练练手,基础知识需要扎实。

public class Plane11 : MonoBehaviour{    public  GameObject m_cubeperfab;    private GameObject m_cube;    public  GameObject m_spherePerfab;    GameObject m_sphere;    Rigidbody m_rigidbody;    void Awake ()    {        m_rigidbody = m_spherePerfab.GetComponent <Rigidbody> ();        for (int i = 0; i < 6; i++) {            for (int j = 0; j < 6; j++) {                m_cube = Instantiate (m_cubeperfab, new  Vector3 (j, i + 0.5f, 0f), Quaternion.identity)as GameObject;                m_cube.GetComponent <MeshRenderer> ().material.color = Color.red;                m_cube.transform.localScale = new Vector3 (0.8f, 0.8f, 0.8f);            }        }    }    Ray m_ray;    RaycastHit m_hit;    Vector3 m_pos;    public Vector3 m_target;    Vector3 dir;    void Update ()    {        if (Input.GetMouseButtonDown (0)) {            m_ray = Camera.main.ScreenPointToRay (Input.mousePosition);            if (Physics.Raycast (m_ray, out m_hit)) {                if (m_hit.rigidbody.tag == "Player") {                    m_pos = m_hit.transform.position;                }            }            m_sphere = Instantiate (m_spherePerfab, Camera.main.transform.position, Quaternion.identity)as GameObject;            dir = m_pos - Camera.main.transform.position;            //值得注意:一定要在预设实例后在添加力。不然预设出来的子弹不能添加力。            //需要注意。            print (dir);            m_sphere.GetComponent <Rigidbody> ().AddForce (dir * 600f);        }    }}

值得注意:一定要在预设实例后在添加力。不然预设出来的子弹不能添加力。需要注意。

0 0
原创粉丝点击