Unity開發詳解之旋轉、移動、碰撞(3/6)


在前兩篇中,我們已經創建好了場景和玩家對象,下面讓玩家對象動起來。

玩家對象旋轉

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

發佈了90 篇原創文章 · 獲贊 80 · 訪問量 22萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章