第一人稱角色移動及自由移動視野(CharacterController實現)


1.創建物體放置如圖:

給Capsule添加CharacterController組件:創建兩個腳本名字分別為Move(控制移動),FreeLook(自由視角觀察)掛在該游戲物體上:

 

2.Move代碼如下:

 

 1 using UnityEngine;
 2 using System.Collections;
 3 
 4 public class Move : MonoBehaviour {
 5 
 6     float speed=5f;  //移動速度
 7     public GameObject camer; //Capsule下面那個攝像機
8
private CharacterController characterController;   9 // Use this for initialization 10 void Start () 11 { 12 characterController = this.GetComponent<CharacterController> (); 13 14 15 } 16 17 // Update is called once per frame 18 void Update () 19 { 20 Vector3 forward = camer.transform.TransformDirection (Vector3.forward);//前后移動 21 float curSpeed = speed * Input.GetAxis ("Vertical"); 22 characterController.SimpleMove(forward * curSpeed); 23 Vector3 v = camer.transform.TransformDirection (Vector3.right);//左右移動 24 float vSpeed = speed * Input.GetAxis ("Horizontal"); 25 characterController.SimpleMove(v * vSpeed); 26 27 } 28 }

3.freeLook代碼如下:

using UnityEngine;
using System.Collections;

public class freeLook : MonoBehaviour 
{
  //視野轉動速度
float speedX=10f; float speedY=10f;
  //上下觀察范圍
float minY=-60; float maxY=60;   //觀察變化量 float rotationX; float rotationY; // Use this for initialization void Start () { } // Update is called once per frame void Update () { rotationX += Input.GetAxis ("Mouse X")*speedX; rotationY += Input.GetAxis ("Mouse Y")*speedY; if (rotationX < 0) { rotationX += 360; } if (rotationX >360) { rotationX -= 360; } rotationY = Mathf.Clamp (rotationY, minY, maxY);   transform.localEulerAngles = new Vector3 (-rotationY, rotationX, 0); } }

4.下面是我的項目連接:

鏈接:http://pan.baidu.com/s/1nva4OHz 密碼:v1az

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM