在前兩篇中,我們已經創建好了場景和玩家對象,下面讓玩家對象動起來。
玩家對象旋轉
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MouseLook : MonoBehaviour {
public float rotateSpeed = 3f;
public float minimumVert = -45f;
public float maximumVert = 45f;
private float _rotationX = 0;
// Use this for initialization
void Start () {
Rigidbody body = GetComponent<Rigidbody>();
if (body != null) {
body.freezeRotation = true;
}
}
// Update is called once per frame
void Update () {
_rotationX -= Input.GetAxis("Mouse Y") * rotateSpeed;
_rotationX = Mathf.Clamp(_rotationX, minimumVert, maximumVert);
float delta = Input.GetAxis("Mouse X") * rotateSpeed;
float rotationY = transform.localEulerAngles.y + delta;
transform.localEulerAngles = new Vector3(_rotationX, rotationY, 0);
}
}
玩家對象移動
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move : MonoBehaviour {
public float speed = 9.0f;
public float gravity = -9.8f;
private CharacterController _characterController;
// Use this for initialization
void Start () {
_characterController = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update () {
float deltaX = Input.GetAxis("Horizontal") * speed;
float deltaZ = Input.GetAxis("Vertical") * speed;
Vector3 movement = new Vector3(deltaX, 0, deltaZ);
movement = Vector3.ClampMagnitude(movement, speed);
movement.y = gravity;
movement *= Time.deltaTime;
movement = transform.TransformDirection(movement);
_characterController.Move(movement);
}
}
剛體碰撞
_characterController.Move(movement);
現在玩家對象在場景中的移動已經沒有問題。接下來引入子彈
遊戲圖示、遊戲下載、源碼下載http://blog.csdn.net/d276031034/article/details/56016801