首先随意创建一个物体作为主角,然后将摄像机调整下位置放到物体头顶,并且添加为子物体。
并且在这个物体上添加一个CharacterController组件。
创建一个脚本名为Move
CharacterController playerController;
Vector3 direction;
public float speed = 10;
public float jumpPower = 3;
public float gravity = 7f;
public float mousespeed = 5f;
float RotationY = 0f;
float RotationX = 0f;
public Transform agretctCamera;
void Start()
{
playerController = this.GetComponent<CharacterController>();
}
void Update()
{
float _horizontal = Input.GetAxis("Horizontal");
float _vertical = Input.GetAxis("Vertical");
if (playerController.isGrounded)
{
direction = new Vector3(_horizontal, 0, _vertical);
if (Input.GetKeyDown(KeyCode.Space))
direction.y = jumpPower;
}
direction.y -= gravity * Time.deltaTime;
playerController.Move(playerController.transform.TransformDirection(direction * Time.deltaTime * speed));
RotationX += Input.GetAxis("Mouse X") * mousespeed;
RotationY -= Input.GetAxis("Mouse Y") * mousespeed;
RotationY = Mathf.Clamp(RotationY, -45f, 45f);
this.transform.eulerAngles = new Vector3(0, RotationX, 0);
agretctCamera.transform.eulerAngles = new Vector3(RotationY, RotationX, 0);
}
}
将此代码放到自己脚本上即可,并且可以在外部修改各种数据,将摄像机拖到相应位置即可。