先把准备好的动画的状态弄好再给人物添加上脚本,别忘了添加一个角色控制器或者刚体
public
KeyCode sprintJoystick = KeyCode.JoystickButton2;
public
KeyCode sprintKeyboard = KeyCode.Space;
private
float
directionDampTime = 10f;
Private
Animator animator;
private
Camera mainCamera;
private
float
turnSpeedMultiplier = 0.2f;
private
float
speed = 0f;
private
float
direction = 0f;
private
bool
isSprinting =
false
;
private
Vector3 targetDirection;
private
Vector2 input;
private
Quaternion freeRotation;
private
float
velocity;
void
Start
()
{
animator = GetComponent<Animator>();
mainCamera = Camera.main;
}
void
Update
()
{
input.x = Input.GetAxis(
“Horizontal”
);
input.y = Input.GetAxis(
“Vertical”
);
// 将速度设置为垂直和水平输入
speed = Mathf.Abs(input.x) + Mathf.Abs(input.y);
speed = Mathf.Clamp(speed, 0f, 1f);
speed = Mathf.SmoothDamp(animator.GetFloat(
“Speed”
), speed,
ref
velocity, 0.1f);
animator.SetFloat(
“Speed”
, speed);
if
(input.y < 0f)
direction = input.y;
else
direction = 0f;
animator.SetFloat(
“Direction”
, direction);
//
设置跑步
isSprinting = ((Input.GetKey(sprintJoystick) || Input.GetKey(sprintKeyboard)) && input != Vector2.zero && direction >= 0f);
animator.SetBool(
“isSprinting”
, isSprinting);
var
forward = mainCamera
.
transform.TransformDirection(Vector3.forward);
forward.y = 0;
//获取referenceTransform的面向右的方向
var
right = mainCamera
.
transform.TransformDirection(Vector3.right);
//根据输入和referenceTransform的右和前方向来决定玩家将面对的方向
targetDirection = input.x * right + input.y * forward;
if
(input != Vector2.zero && targetDirection.magnitude > 0.1f)
{
Vector3 lookDirection = targetDirection.normalized;
freeRotation = Quaternion.LookRotation(lookDirection, transform.up);
var
diferenceRotation = freeRotation.eulerAngles.y – transform.eulerAngles.y;
var
eulerY = transform.eulerAngles.y;
if
(diferenceRotation < 0 || diferenceRotation > 0) eulerY = freeRotation.eulerAngles.y;
var
euler =
new
Vector3(0, eulerY, 0);
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.Euler(euler), directionDampTime * turnSpeedMultiplier * Time.deltaTime);
}
}