一共用到三个脚本:
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<Rigidbody> ().AddForce (fwd * 100);
}
}
注意:
墙,记得要添加Rigidbody组件。
CameraController.cs 要外挂到摄像机上面。
新建空对象GameObject来挂WallController.cs。
子弹预制体RedBullet,要挂上RedBullet.cs。