第一人称角色移动及自由移动视野(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