当前位置: 首页 > 工具软件 > LuoYing RPG > 使用案例 >

RPG类游戏主角移动的代码

顾俊茂
2023-12-01

本来RPG类游戏主角移动的代码没什么特别,

这里要指出的是在使用character.simpleMove(moveSpeed * transform.TransformDirection(new Vector3(0, 0, 1)))

来移动,但是当角色在斜坡上由于角色角度的变化而会出现方向改变不能直接到达目的地的问题。这个问题

我尝试了好多方法,但是由于自己判断不准确,好久都没有解决。所以找到视频的解决办法后这里记录一下。

下面是代码,红色部分为斜坡方向问题的解决方案:

using UnityEngine;
using System.Collections;

public class CharacterMove : MonoBehaviour
{

    bool mousePressing;
    CharacterController player;
    public float moveSpeed;
    public GameObject clickEffect;
    float preDistance;
    //表示是否按下鼠标
    bool pressingMouse;
    Vector3 targetPos;


    // Use this for initialization
    void Start()
    {
      
        targetPos = transform.position;
        player = GetComponent<CharacterController>();
    }

  

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            pressingMouse = true;
            ShowClickEfx();
        }



        if (Input.GetMouseButtonUp(0))
        {
            pressingMouse = false;
        }

        Move();


    }

    private void Move()
    {

        if (pressingMouse)
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hitInfo;
            if (Physics.Raycast(ray, out hitInfo))
            {
                if (hitInfo.collider.tag == GameTags.ground)
                {

                    pressingMouse = true;
                    targetPos = hitInfo.point;
                    targetPos.y = transform.position.y;
                }
            }
            transform.LookAt(targetPos);


        }
        if (Vector3.Distance(targetPos, transform.position) > 0.5)
        {
            player.SimpleMove(moveSpeed * transform.TransformDirection(new Vector3(0, 0, 1)));
            CharacterState._instance.animstate = AnimState.Run;
            CharacterAnim.Instance.PlayAnim();
            <span style="color:#ff6666;">targetPos.y = transform.position.y;
            transform.LookAt(targetPos);</span>
           
        }




        if (Vector3.Distance(targetPos, transform.position) < 0.5)
        {
            CharacterState._instance.animstate = AnimState.Idle;
            CharacterAnim.Instance.PlayAnim();
        }

    }

    private void ShowClickEfx()
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hitInfo;
        if (Physics.Raycast(ray, out hitInfo))
        {
            if (hitInfo.collider.tag == GameTags.ground)
            {
                GameObject.Instantiate(clickEffect, hitInfo.point + new Vector3(0, 0.05f, 0), Quaternion.identity);

            }

        }
    }
}
    

 类似资料: