注意
- GetAxisRaw 和 GetAxis的区别:前者更好控制,后者按下后会从0过度到1或-1,比较平滑
- 鼠标左右移动,角色以自身y轴旋转,子物体摄像机跟随;鼠标上下移动,摄像机以自身x周旋转
ps:通过代码赋值,赋值在Awake中实现,但是需要注意”Camera”这个游戏对象名称
截图
PlayerInput
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerInput : MonoBehaviour {
[SerializeField]
private float speed = 5f;
[SerializeField]
private float lookSensitivity = 8f;
private PlayerController controller;
void Awake() {
controller = gameObject.GetComponent<PlayerController>();
// 隐藏鼠标
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update() {
float xMov = Input.GetAxisRaw("Horizontal");
float yMov = Input.GetAxisRaw("Vertical");
Vector3 velocity = (transform.right * xMov + transform.forward * yMov).normalized * speed;
controller.Move(velocity);
float xMouse = Input.GetAxisRaw("Mouse X");
float yMouse = Input.GetAxisRaw("Mouse Y");
Vector3 yRotation = new Vector3(0f, xMouse, 0f) * lookSensitivity;
Vector3 xRotation = new Vector3(-yMouse, 0f, 0f) * lookSensitivity;
controller.Rotate(yRotation, xRotation);
}
}
PlayerController
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour {
private Rigidbody rb;
private Camera cam;
private Vector3 velocity = Vector3.zero; // 移动速度
private Vector3 yRotation = Vector3.zero; // 人物旋转
private Vector3 xRotation = Vector3.zero; // 相机旋转
void Awake() {
rb = gameObject.GetComponent<Rigidbody>();
// 这里只是获取了相机gameObject下的Camera组件,而不是相机gameObject,在第二次课中还需要gameObject下的ClientNetwork,不然客户端没办法通过鼠标左右操作摄像机视角
cam = GameObject.Find("Camera").GetComponent<Camera>();
}
private void FixedUpdate() {
PerformMovement();
PerformRotation();
}
public void Move(Vector3 _velocity) {
velocity = _velocity;
}
private void PerformMovement() {
if(velocity != Vector3.zero) {
rb.MovePosition(rb.position + velocity * Time.fixedDeltaTime);
}
}
public void Rotate(Vector3 _yRotation, Vector3 _xRotation) {
yRotation = _yRotation;
xRotation = _xRotation;
}
private void PerformRotation() {
if(yRotation != Vector3.zero) {
rb.transform.Rotate(yRotation);
}
if(xRotation != Vector3.zero) {
cam.transform.Rotate(xRotation);
}
}
}