U3D游戏开发中控制主角人物移动

发布时间:2024年01月18日

本篇将介绍主角人物移动的代码逻辑以及动画控制。

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);
    }
}

以上代码如有疑问欢迎私聊问我,希望我的笔记对您有所帮助。喜欢就点赞收藏吧!

文章来源:https://blog.csdn.net/2303_76354097/article/details/135634766
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。