第三人称移动&动画控制器、摄像机跟随
1. 第三人称移动&动画控制器
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Timeline;
/// <summary>
/// 移动
/// </summary>
public class Move : MonoBehaviour
{
private Animator _animator;
private Rigidbody _rb;
public float walkSpeed;
public float runSpeed;
private float currentSpeed;
private float horizontal;
private float vertical;
//是否处于跑步态
private bool isRunning;
private bool isJumping;
private bool isGrounded = true;
private Vector3 _direction;
//初始化
void Start()
{
//获取组件
_animator=GetComponent<Animator>();
_rb=GetComponent<Rigidbody>();
walkSpeed = 2.0f;
runSpeed = 4.0f;
}
//获取输入
void Update()
{
horizontal = Input.GetAxis("Horizontal");
vertical = Input.GetAxis("Vertical");
if (Input.GetKeyDown(KeyCode.LeftShift)){
isRunning = true;
}
if (Input.GetKeyUp(KeyCode.LeftShift)){
isRunning = false;
}
if (Input.GetKeyDown(KeyCode.Space))
{
_animator.SetTrigger("jump");
isJumping = true;
}
else
{
isJumping = false;
}
}
private void LateUpdate()
{
if (isJumping)
{
if (isGrounded == true)
{
_rb.velocity += new Vector3(0, 1, 0); //添加加速度
_rb.AddForce(Vector3.up * 5, ForceMode.VelocityChange); //给刚体一个向上的力,力的大小为Vector3.up*mJumpSpeed
isGrounded = false;
}
}
}
//对刚体的操作,放入FixedUpdate
private void FixedUpdate()
{
//获取方向
_direction=new Vector3(horizontal, 0, vertical).normalized;//获取标准向量的方向
//用户有输入时旋转加移动
if (_direction.magnitude >0)//magnitude:向量长度
{
//旋转
transform.rotation=Quaternion.LookRotation(_direction,Vector3.up);
//移动
Vector3 p = transform.position;//获取到当前的位置
if(isRunning)
{
p += _direction * runSpeed * Time.deltaTime;
}
else
{
p += _direction * walkSpeed * Time.deltaTime;
}
//使用刚体移动
_rb.MovePosition(p);
}
if (isRunning)
{
currentSpeed = new Vector3(horizontal, 0, vertical).magnitude * runSpeed;
}
else
{
currentSpeed = new Vector3(horizontal, 0, vertical).magnitude * walkSpeed;
}
_animator.SetFloat("speed", currentSpeed);
}
// 落地检测(若不在地面不进行第二次跳跃)
void OnCollisionEnter(Collision collision)
{
_animator.SetBool("jump", false);
isGrounded = true;
}
}
2. 摄像机跟随
1. 虚拟摄像机
- Window–>Package Manage 下载组件Cinemachine
- 在场景中创建虚拟摄像机
- 右键选择Cinemachine
- 双击虚拟摄像机
- 将 Follow 和 Look At 挂载上玩家
- 将 Body调为 Transposer
- 将 Binging Mode 调整为World Space
- 调整参数,找到最合适的位置
- 效果 —— 能够达到 45° 角度跟随
2. 编写代码相机跟随
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraFollow : MonoBehaviour
{
private Vector3 offset;//记录相机和主角的位置偏移
private Transform playerTransform;//获取玩家位置
void Stat()
{
playerTransform = GameObject.FindGameObjectWithTag("Player").transform;//寻找Player标签的物体作为跟随对象
offset = transform.position - playerTransform.position;
}
void Update()
{
transform.position = playerTransform.position + offset;
}
}
效果同上述虚拟摄像机方法。