欢迎光临散文网 会员登陆 & 注册

使用unity制作一个宝可梦——3.添加碰撞体

2023-06-08 21:52 作者:立志看完尚硅谷  | 我要投稿

最后一点没看懂,反正照着写了,贴个代码


using System.Collections;

using System.Collections.Generic;

using UnityEngine;


//这是一个控制玩家的类,实现的功能有:

//1.上下左右移动

//2.播放移动动画


public class PlayerController : MonoBehaviour

{

  public float moveSpeed; //玩家的移动速度

  public LayerMask solidObjectsLayer; //获取房屋的图层


  private bool isMoving; //是否处在移动

  private Animator animator; //定义玩家的动画的状态机


  private void Awake() //Awake():生命周期函数,当组件被实例化并启用时,该方法将在其它方法之前调用一次

  {

    animator = GetComponent<Animator>(); //获取到玩家的状态机

  }


  private void Update()

  {

    if (!isMoving)

    {

      var input = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));

     


      if (input.x != 0) input.y = 0; //限制角色走斜线


      if (input != Vector2.zero) //如果输入的值不为0

      {

        //将输入的x,y值赋予给moveX,moveY,用来控制角色的动画状态

        animator.SetFloat("moveX",input.x);

        animator.SetFloat("moveY", input.y);


        var targetPos = transform.position; //targetPos:目标的位置

        targetPos.x += input.x;     //x方向加上垂直方向输入进来的值

        targetPos.y += input.y;     //y方向加上水平方向输入进来的值


        if (isWalkable(targetPos)) //如果移动没有被阻塞

          StartCoroutine(Move(targetPos)); //开启玩家移动的协程,将目标的位置作为参数传递过去

      }

    }


    animator.SetBool("isMoving",isMoving); //将isMoving的状态赋予给状态机

  }



  IEnumerator Move(Vector3 targetPos)

  {

    isMoving = true;


    // 循环判断当前位置与目标位置之间的距离是否大于一个很小的数值

    while ((targetPos - transform.position).sqrMagnitude > Mathf.Epsilon)

    {

      // 计算每帧应该移动的距离,并让物体朝目标位置移动一步

      transform.position = Vector3.MoveTowards(transform.position, targetPos, moveSpeed * Time.deltaTime);

      // 让程序等待下一帧再执行

      yield return null;

    }

    // 直接将物体移动到精确定位到目标位置上,避免偏差堆积

    transform.position = targetPos;


    isMoving = false;

  }



  private bool isWalkable(Vector3 targetPos) //判断行走是否被阻塞

  {

    if (Physics2D.OverlapCircle(targetPos, 0.2f, solidObjectsLayer) != null)

    {

      return false;

    }

    return true;

  }

}

使用unity制作一个宝可梦——3.添加碰撞体的评论 (共 条)

分享到微博请遵守国家法律