本篇将介绍主角人物移动的代码逻辑以及动画控制。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 一个用于控制物体状态的枚举
/// </summary>
public enum ControlWalkState
{
Moving,
Idle
}
/// <summary>
/// 一个用于控制人物移动的类
/// </summary>
public class PlayerMove : MonoBehaviour
{
//设置主角的移动速度
public float speed = 4;
//设置主角的默认状态
public ControlWalkState state = ControlWalkState.Idle;
public bool isMoving=false;
private PlayerDir dir;
private PlayerAttack attack;
private CharacterController controller;
// Start is called before the first frame update
void Start()
{
dir=this.GetComponent<PlayerDir>();
controller = this.GetComponent<CharacterController>();
attack = this.GetComponent<PlayerAttack>();
}
// Update is called once per frame
void Update()
{
if (attack.state == PlayerState.ControlWalk)
{
float distance = Vector3.Distance(dir.targetPosition, transform.position);
if (distance > 0.1f)
{
isMoving = true;
state = ControlWalkState.Moving;
controller.SimpleMove(transform.forward * speed);
}
else
{
isMoving = false;
state = ControlWalkState.Idle;
}
}
}
public void SimpleMove(Vector3 targetPos)
{
transform.LookAt(targetPos);
controller.SimpleMove(transform.forward * speed);
}
}
以上代码如有疑问欢迎私聊问我,希望我的笔记对您有所帮助。喜欢就点赞收藏吧!