第一人称视角操作
此功能主要是借鉴YouTube上一个博主的教程,写的蛮好我就搬运过来让大家也试试。
1、控制对象与镜头是子父级关系
2、控制器对象添加CharacterController,Rigidbody组件如下:
3、重头戏:创建PlayerController脚本并比此脚本挂到控制器上
其原理是:左右旋转是控制父物体的欧拉角的Y轴
transform.Rotate(0, Input.GetAxis("Mouse X") * sensetivity,0);
上下点头是子物体相机的欧拉角Z轴
playerCamera.Rotate(-Input.GetAxis("Mouse Y") * sensetivity, 0, 0);
水平方向
moveDirection = new Vector3(Input.GetAxis("Horizontal")*moveSpeed, moveDirection.y, Input.GetAxis("Vertical")*moveSpeed);
moveDirection = transform.TransformDirection(moveDirection);
跳跃:文章来源:https://www.toymoban.com/news/detail-859308.html
if (controller.isGrounded)
{
if (Input.GetButton("Jump"))
moveDirection.y = jumpForce;
else
moveDirection.y = 0;
}
移动文章来源地址https://www.toymoban.com/news/detail-859308.html
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection*Time.deltaTime);
4、源代码奉上:
using UnityEngine;
public class PlayerController : MonoBehaviour
{
[SerializeField] private float moveSpeed = 6f;
[SerializeField] private float jumpForce = 10;
[SerializeField] private float gravity = 15f;
private Vector3 moveDirection;
[Header("Camera details")]
public float sensetivity = 1f;
private Transform playerCamera;
private CharacterController controller;
void Start()
{
controller = GetComponent<CharacterController>();
playerCamera = GetComponentInChildren<Camera>().transform;
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
void Update()
{
transform.Rotate(0, Input.GetAxis("Mouse X") * sensetivity,0);
playerCamera.Rotate(-Input.GetAxis("Mouse Y") * sensetivity, 0, 0);
if (playerCamera.localRotation.eulerAngles.y != 0)
playerCamera.Rotate(Input.GetAxis("Mouse Y")*sensetivity,0,0);
moveDirection = new Vector3(Input.GetAxis("Horizontal")*moveSpeed, moveDirection.y, Input.GetAxis("Vertical")*moveSpeed);
moveDirection = transform.TransformDirection(moveDirection);
if (controller.isGrounded)
{
if (Input.GetButton("Jump"))
moveDirection.y = jumpForce;
else
moveDirection.y = 0;
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection*Time.deltaTime);
}
}
到了这里,关于Unity 第一人称视角控制移动、旋转的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!