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

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

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  ();

        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  ().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  ().AddForce (dir * 600f);
        }
    }

}

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

你可能感兴趣的:(边学边记)