文章目录
- 一、目标
- 二、代码
- 三、收获
- 四、总结
一、目标
- 控制人物移动,奔跑,跳跃
- 人物视角跟随鼠标
- 移动时有背景音乐
二、代码
using System;
using System.Linq;
using UnityEngine;
namespace FPSControllerLPFP
{
// Manages a first person character
// RequitrComponent的作用是,直接将对象的组件进行绑定,而不需要从incpector去进行设置,避免错误
[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(CapsuleCollider))]
[RequireComponent(typeof(AudioSource))]
public class FpsControllerLPFP : MonoBehaviour
{
#pragma warning disable 649
[Header("Arms")]
//Header:是用来修改在inspector面板上属性的标题的
[Tooltip("The transform component that holds the gun camera."), SerializeField]
//Tooltip:属性提示,他是干什么的
//SerializedFiled的作用是为private的字段也能够在inspector面板显示
private Transform arms;
[Tooltip("The position of the arms and gun camera relative to the fps controller GameObject."), SerializeField]
private Vector3 armPosition;
[Header("Audio Clips")]
[Tooltip("The audio clip that is played while walking."), SerializeField]
private AudioClip walkingSound;
[Tooltip("The audio clip that is played while running."), SerializeField]
private AudioClip runningSound;
[Header("Movement Settings")]
[Tooltip("How fast the player moves while walking and strafing."), SerializeField]
private float walkingSpeed = 5f;
[Tooltip("How fast the player moves while running."), SerializeField]
private float runningSpeed = 9f;
[Tooltip("Approximately the amount of time it will take for the player to reach maximum running or walking speed."), SerializeField]
private float movementSmoothness = 0.125f;
[Tooltip("Amount of force applied to the player when jumping."), SerializeField]
private float jumpForce = 35f;
[Header("Look Settings")]
[Tooltip("Rotation speed of the fps controller."), SerializeField]
private float mouseSensitivity = 7f;
[Tooltip("Approximately the amount of time it will take for the fps controller to reach maximum rotation speed."), SerializeField]
private float rotationSmoothness = 0.05f;
[Tooltip("Minimum rotation of the arms and camera on the x axis."),
SerializeField]
private float minVerticalAngle = -90f;
[Tooltip("Maximum rotation of the arms and camera on the axis."),
SerializeField]
private float maxVerticalAngle = 90f;
[Tooltip("The names of the axes and buttons for Unity's Input Manager."), SerializeField]
private FpsInput input;//自定义的输入类,作用:
#pragma warning restore 649
private Rigidbody _rigidbody;
private CapsuleCollider _collider;
private AudioSource _audioSource;
private SmoothRotation _rotationX;//作用:包含了当前X轴方向上的偏转和速度
private SmoothRotation _rotationY;//作用:包含了当前Y轴方向上的偏转和速度
private SmoothVelocity _velocityX;
private SmoothVelocity _velocityZ;
private bool _isGrounded;//判断是否落地
private readonly RaycastHit[] _groundCastResults = new RaycastHit[8]; //触地
private readonly RaycastHit[] _wallCastResults = new RaycastHit[8];//触墙
/// Initializes the FpsController on start.
private void Start()
{
_rigidbody = GetComponent<Rigidbody>();
_rigidbody.constraints = RigidbodyConstraints.FreezeRotation;//全部锁定旋转,使得该刚体不能旋转
_collider = GetComponent<CapsuleCollider>();
_audioSource = GetComponent<AudioSource>();
arms = transform;
//AssignCharactersCamera();//初始化手臂的位置
_audioSource.clip = walkingSound;//步行的音乐
_audioSource.loop = true;//是否循环
//返回初始的x轴角度
_rotationX = new SmoothRotation(RotationXRaw);
_rotationY = new SmoothRotation(RotationYRaw);
_velocityX = new SmoothVelocity();
_velocityZ = new SmoothVelocity();
//这句话什么意思?锁定鼠标并隐藏
Cursor.lockState = CursorLockMode.Locked;
//设置旋转角度的限制
ValidateRotationRestriction();
}
/// Clamps <see cref="minVerticalAngle"/> and <see cref="maxVerticalAngle"/> to valid values and
/// ensures that <see cref="minVerticalAngle"/> is less than <see cref="maxVerticalAngle"/>.
private void ValidateRotationRestriction()
{
//该函数为了防止开发者设置错了参数,并限制Y轴上可以看到的角度
minVerticalAngle = ClampRotationRestriction(minVerticalAngle, -90, 90);
maxVerticalAngle = ClampRotationRestriction(maxVerticalAngle, -90, 90);
if (maxVerticalAngle >= minVerticalAngle) return;
Debug.LogWarning("maxVerticalAngle should be greater than minVerticalAngle.");
var min = minVerticalAngle;
minVerticalAngle = maxVerticalAngle;
maxVerticalAngle = min;
}
private static float ClampRotationRestriction(float rotationRestriction, float min, float max)
{
if (rotationRestriction >= min && rotationRestriction <= max) return rotationRestriction;
var message = string.Format("Rotation restrictions should be between {0} and {1} degrees.", min, max);
Debug.LogWarning(message);
return Mathf.Clamp(rotationRestriction, min, max);
}
/// Checks if the character is on the ground.
private void OnCollisionStay()
{
//当玩家触地时,持续过程中,碰撞体还需要好好看看
var bounds = _collider.bounds;
var extents = bounds.extents;
var radius = extents.x - 0.01f;
Physics.SphereCastNonAlloc(bounds.center, radius, Vector3.down,
_groundCastResults, extents.y - (radius * 0.5f), ~0, QueryTriggerInteraction.Ignore);
if (!_groundCastResults.Any(hit => hit.collider != null && hit.collider != _collider)) return;
for (var i = 0; i < _groundCastResults.Length; i++)
{
_groundCastResults[i] = new RaycastHit();
}
_isGrounded = true;
}
/// Processes the character movement and the camera rotation every fixed framerate frame.
private void FixedUpdate()
{
// FixedUpdate is used instead of Update because this code is dealing with physics and smoothing.
RotateCameraAndCharacter();//角色移动
MoveCharacter();//角色移动
//_isGrounded = false;
}
/// Moves the camera to the character, processes jumping and plays sounds every frame.
private void Update()
{
arms.position = transform.position + transform.TransformVector(armPosition);
Jump();
PlayFootstepSounds();
}
private void RotateCameraAndCharacter()
{
var rotationX = _rotationX.Update(RotationXRaw, rotationSmoothness);//更新方向x
var rotationY = _rotationY.Update(RotationYRaw, rotationSmoothness);//更新方向y
var clampedY = RestrictVerticalRotation(rotationY);//Y轴上有限制要进行判断
_rotationY.Current = clampedY;
//Vector.up代表一个y方向上的单位向量
var worldUp = arms.InverseTransformDirection(Vector3.up);//InverseTransformDirection()将vector从世界空间变换成本地空间
var rotation = arms.rotation *
Quaternion.AngleAxis(rotationX, worldUp) * //Quaternion.AngleAxis创建围绕worldUp旋转的角度rotation worldup是指Y轴
Quaternion.AngleAxis(clampedY, Vector3.left);//Quaternion.AngleAxis创建围绕left旋转的角度,最后返回Quaternion
transform.eulerAngles = new Vector3(0f, rotation.eulerAngles.y, 0f);//为什么这里只把y轴的欧拉角复制了,其他的轴都设置为0呢?
arms.rotation = rotation;//将计算好的旋转角度给arms,去进行旋转
}
/// Returns the target rotation of the camera around the y axis with no smoothing.
private float RotationXRaw
{
//返回鼠标移动后目标旋转的y轴角度
get { return input.RotateX * mouseSensitivity; }
}
/// Returns the target rotation of the camera around the x axis with no smoothing.
private float RotationYRaw
{
//返回鼠标移动后目标旋转的X轴角度
get { return input.RotateY * mouseSensitivity; }
}
/// Clamps the rotation of the camera around the x axis
/// between the <see cref="minVerticalAngle"/> and <see cref="maxVerticalAngle"/> values.
private float RestrictVerticalRotation(float mouseY)
{
var currentAngle = NormalizeAngle(arms.eulerAngles.x);
var minY = minVerticalAngle + currentAngle;
var maxY = maxVerticalAngle + currentAngle;
return Mathf.Clamp(mouseY, minY + 0.01f, maxY - 0.01f);
}
/// Normalize an angle between -180 and 180 degrees.
/// <param name="angleDegrees">angle to normalize</param>
/// <returns>normalized angle</returns>
private static float NormalizeAngle(float angleDegrees)
{
while (angleDegrees > 180f)
{
angleDegrees -= 360f;
}
while (angleDegrees <= -180f)
{
angleDegrees += 360f;
}
return angleDegrees;
}
private void MoveCharacter()
{
var direction = new Vector3(input.Move, 0f, input.Strafe).normalized;//XY轴的移动
var worldDirection = transform.TransformDirection(direction);//本地空间变成世界空间
var velocity = worldDirection * (input.Run ? runningSpeed : walkingSpeed);//方向乘大小等于速度
//Checks for collisions so that the character does not stuck when jumping against walls.
var intersectsWall = CheckCollisionsWithWalls(velocity);
if (intersectsWall)
{
//如果没有着地直接返回不要移动
_velocityX.Current = _velocityZ.Current = 0f;//并把水平方向的速度全部置为0
return;
}
var smoothX = _velocityX.Update(velocity.x, movementSmoothness);
var smoothZ = _velocityZ.Update(velocity.z, movementSmoothness);
var rigidbodyVelocity = _rigidbody.velocity;//当前的速度
var force = new Vector3(smoothX - rigidbodyVelocity.x, 0f, smoothZ - rigidbodyVelocity.z);//向量相减得到新的速度方向
_rigidbody.AddForce(force, ForceMode.VelocityChange);//加速度
//设置刚体的移动,
}
private bool CheckCollisionsWithWalls(Vector3 velocity)
{
if (_isGrounded) return false;
var bounds = _collider.bounds;
var radius = _collider.radius;
var halfHeight = _collider.height * 0.5f - radius * 1.0f;
var point1 = bounds.center;
point1.y += halfHeight;
var point2 = bounds.center;
point2.y -= halfHeight;
Physics.CapsuleCastNonAlloc(point1, point2, radius, velocity.normalized, _wallCastResults,
radius * 0.04f, ~0, QueryTriggerInteraction.Ignore);
var collides = _wallCastResults.Any(hit => hit.collider != null && hit.collider != _collider);
if (!collides) return false;
for (var i = 0; i < _wallCastResults.Length; i++)
{
_wallCastResults[i] = new RaycastHit();
}
return true;
}
private void Jump()
{
if (!_isGrounded || !input.Jump) return;
_isGrounded = false;
_rigidbody.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);//添加一个向上的力模拟跳起来
}
private void PlayFootstepSounds()
{
if (_isGrounded && _rigidbody.velocity.sqrMagnitude > 0.1f)
{
//着地并且移动
_audioSource.clip = input.Run ? runningSound : walkingSound;
if (!_audioSource.isPlaying)
{
_audioSource.Play();
}
}
else
{
if (_audioSource.isPlaying)
{
//如果停下来或者跳起来了,声音暂停
_audioSource.Pause();
}
}
}
/// A helper for assistance with smoothing the camera rotation.
private class SmoothRotation
{
private float _current;
private float _currentVelocity;
public SmoothRotation(float startAngle)
{
_current = startAngle;
}
/// Returns the smoothed rotation.
public float Update(float target, float smoothTime)
{
return _current = Mathf.SmoothDampAngle(_current, target, ref _currentVelocity, smoothTime);
}
public float Current
{
set { _current = value; }
}
}
/// A helper for assistance with smoothing the movement.
private class SmoothVelocity
{
private float _current;
private float _currentVelocity;
/// Returns the smoothed velocity.
public float Update(float target, float smoothTime)
{
//平滑过渡
return _current = Mathf.SmoothDamp(_current, target, ref _currentVelocity, smoothTime);
}
public float Current
{
set { _current = value; }
}
}
/// Input mappings
[Serializable]
private class FpsInput
{
[Tooltip("The name of the virtual axis mapped to rotate the camera around the y axis."),
SerializeField]
private string rotateX = "Mouse X";
[Tooltip("The name of the virtual axis mapped to rotate the camera around the x axis."),
SerializeField]
private string rotateY = "Mouse Y";
[Tooltip("The name of the virtual axis mapped to move the character back and forth."),
SerializeField]
private string move = "Horizontal";
[Tooltip("The name of the virtual axis mapped to move the character left and right."),
SerializeField]
private string strafe = "Vertical";
[Tooltip("The name of the virtual button mapped to run."),
SerializeField]
private string run = "Fire3";
[Tooltip("The name of the virtual button mapped to jump."),
SerializeField]
private string jump = "Jump";
///返回映射的虚拟轴的值,以绕y轴旋转相机
/// Returns the value of the virtual axis mapped to rotate the camera around the y axis.
public float RotateX
{
get { return Input.GetAxisRaw(rotateX); }
}
/// Returns the value of the virtual axis mapped to rotate the camera around the x axis.
public float RotateY
{
get { return Input.GetAxisRaw(rotateY); }
}
/// Returns the value of the virtual axis mapped to move the character back and forth.
public float Move
{
get { return Input.GetAxisRaw(move); }
}
/// Returns the value of the virtual axis mapped to move the character left and right.
public float Strafe
{
get { return Input.GetAxisRaw(strafe); }
}
/// Returns true while the virtual button mapped to run is held down.
public bool Run
{
//按键触发
get { return Input.GetButton(run); }
}
/// Returns true during the frame the user pressed down the virtual button mapped to jump.
public bool Jump
{
get { return Input.GetButtonDown(jump); }
}
}
}
}
三、收获
-
FpsInput
封装了与输入相关的操作 - 世界坐标系和本地坐标系的应用场景,分别有什么作用。
- 旋转时涉及到四元数
- 物体移动要素:力,方向,速度
四、总结
- 遇到问题及时记录,解决问题及时总结
- 动画系统/物理系统/音效系统及时学习