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

weixin_30639719發表於2020-04-05

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

 

轉載於:https://www.cnblogs.com/lichuangblog/p/6685800.html

相關文章