Unity 打倒围墙(简单)

Unity 打倒围墙(简单)_第1张图片
8B4E9840-A97A-4E44-AAE5-641EEDA1387F.png
Untitled2017051117472222.gif

一共用到三个脚本:
CameraController.cs -> 给摄像机移动操作(左右前后移动、左右旋转)
WallController.cs -> 负责响应点击鼠标左键加载生成子弹
RedBullet.cs -> 给子弹一个力发射出去进行物理碰撞

public class CameraController : MonoBehaviour {
    //移动速度
    public float TranslateSpeed = 5;

    //旋转速度
    public float RotateSpeed = 50;

    // Use this for initialization
    void Start () {
        
    }
    
    // Update is called once per frame
    void Update () {
        if (Input.GetKey (KeyCode.A)) {
            //向左移动
            transform.Translate (Vector3.right * Time.deltaTime * (-TranslateSpeed));
        } else if (Input.GetKey (KeyCode.D)) {
            //向右移动
            transform.Translate (Vector3.right * Time.deltaTime * (TranslateSpeed));
        } else if (Input.GetKey (KeyCode.W)) {
            //向前移动
            transform.Translate (Vector3.forward * Time.deltaTime * (TranslateSpeed));
        } else if (Input.GetKey (KeyCode.S)) {
            //向后移动
            transform.Translate (Vector3.forward * Time.deltaTime * (-TranslateSpeed));
        } else if (Input.GetKey (KeyCode.Q)) {
            //向左旋转
            transform.Rotate (Vector3.up * Time.deltaTime * (-RotateSpeed));
        } else if (Input.GetKey (KeyCode.E)) {
            //向左旋转
            transform.Rotate (Vector3.up * Time.deltaTime * (RotateSpeed));
        }
    }
}
public class WallController : MonoBehaviour {
    private GameObject goBullet;
    private GameObject bullet;

    private GameObject mainCamera;

    // Use this for initialization
    void Start () {
        goBullet = Resources.Load ("RedBullet") as GameObject;

        mainCamera = GameObject.Find ("Main Camera");
    }

    // Update is called once per frame
    void Update () {
        if (Input.GetButtonDown ("Fire1")) {//按下鼠标左键发射子弹
            bullet = Instantiate (goBullet);//将预制体生成对象

            bullet.transform.position = mainCamera.transform.position;
//          bullet.transform.position = new Vector3(0.0f,0.5f,-11.0f);
        }
    }
}
public class RedBullet : MonoBehaviour {
    Vector3 fwd;

    // Use this for initialization
    void Start () {
        fwd = transform.InverseTransformDirection (Vector3.forward);
    }

    // Update is called once per frame
    void Update () {
        GetComponent ().AddForce (fwd * 100);
    }
}

注意:
墙,记得要添加Rigidbody组件。
CameraController.cs 要外挂到摄像机上面。
新建空对象GameObject来挂WallController.cs。
子弹预制体RedBullet,要挂上RedBullet.cs。

你可能感兴趣的:(Unity 打倒围墙(简单))