Unity first person controller (FirstPersonController)
first person structure
Camera placement
CharacterController
The basic idea:
Control the camera aroundx-axis rotation=> characterup and downView rotation,
control of the body (cylinder)aboutRotation => Script to control the characteraboutPerspective rotation.
simulate gravity
(Disadvantages of using Character)
code
MouseLook.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MouseLook : MonoBehaviour
{
//sensitivity => 灵敏度
public float MouseSensitivity = 100f;
public Transform PlayerBody;
private float XRotation = 0f;
// Start is called before the first frame update
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update()
{
float MouseX = Input.GetAxis("Mouse X") * MouseSensitivity * Time.deltaTime;
float MouseY = Input.GetAxis("Mouse Y") * MouseSensitivity * Time.deltaTime;
XRotation -= MouseY;
XRotation = Mathf.Clamp(XRotation, -90f, 90f);
transform.localRotation = Quaternion.Euler(XRotation, 0f, 0f);
PlayerBody.Rotate(Vector3.up * MouseX);
}
}
PlayerMovement.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public CharacterController CharacterController;
[Header("Move")]
public float Speed = 12f;
public float Gravity = 20f;
private Vector3 m_Velocity;
[Space]
[Header("IsGrounded")]
public Transform GroundCheck;
public float GroundDistance;
public LayerMask GroundMask;
private bool m_IsGrounded;
[Header("Jump")]
public float JumpHeight;
// Update is called once per frame
void Update()
{
// 落地检测
m_IsGrounded = Physics.CheckSphere(GroundCheck.position, GroundDistance, GroundMask);
if (m_IsGrounded && m_Velocity.y < 0)
{
m_Velocity.y = -2;
}
//平面移动
float x = Input.GetAxis("Horizontal");
float y = Input.GetAxis("Vertical");
Vector3 MoveDir = transform.right * x + transform.forward * y;
CharacterController.Move(MoveDir * Speed * Time.deltaTime);
//自由落体
m_Velocity.y -= Time.deltaTime * Gravity;
CharacterController.Move(m_Velocity * Time.deltaTime);
//跳跃
if (Input.GetButtonDown("Jump")
&& m_IsGrounded)
{
m_Velocity.y = Mathf.Sqrt(JumpHeight * 2f * Gravity);
}
}
}
some small extensions
Cursor.LockState
CursorLockMode
Locked: Lock the cursor onscreen center,Not displayable.
Confined: Lock the cursor onWithin the game interface, cannot move out, cursorwill be displayed。