我们在玩第一人称游戏通常需要控制人物视角和位置,如WSAD控制前后左右,鼠标控制视角,我们只需要创建一个脚本挂载到主摄像机下面即可,话不多说,直接上代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraController : MonoBehaviour
{
public float speed;
private Camera camera;
// Use this for initialization
void Start()
{
camera = GetComponentInChildren<Camera>();
}
// Update is called once per frame
void Update()
{
// 得到鼠标当前位置
float mouseX = Input.GetAxis ("Mouse X") * speed;
float mouseY = Input.GetAxis ("Mouse Y") * speed;
// 设置照相机和Player的旋转角度,X,Y值需要更具情况变化位置
camera.transform.localRotation = camera.transform.localRotation * Quaternion.Euler (-mouseY, 0, 0);
transform.localRotation = transform.localRotation * Quaternion.Euler (0, mouseX, 0);
float x = Input.GetAxis("Horizontal") * Time.deltaTime * speed;//左右移动
float z = Input.GetAxis("Vertical") * Time.deltaTime * speed;//前后移动
transform.Translate(x, 0, z);//相机的移动
}
}
挂载后设置速度: