团结,当他遇到障碍或界限时停止移动玩家

时间:2018-03-12 10:57:51

标签: unity3d

我使用MoveTowards实现移动系统。我有几个Collider2D障碍,不应该被我的对象重叠。

void Update()
{
    if (playerType == PLAYER_TYPE.PLAYER_ONE)
    {
        if (Input.GetKey(KeyCode.W))
            CheckIfAbleThenMove(gameObject.transform.position + transform.up * speed * Time.deltaTime);

        if (Input.GetKey(KeyCode.S))
            CheckIfAbleThenMove(gameObject.transform.position + (-1) * transform.up * speed * Time.deltaTime);

        if (Input.GetKey(KeyCode.D))
            CheckIfAbleThenMove(gameObject.transform.position + transform.right * speed * Time.deltaTime);

        if (Input.GetKey(KeyCode.A))
            CheckIfAbleThenMove(gameObject.transform.position + (-1) * transform.right * speed * Time.deltaTime);
    }

    float step = moveTowardsSpeed * Time.deltaTime;
    gameObject.transform.position = Vector3.MoveTowards(transform.position, target, step);
}

  private void CheckIfAbleThenMove(Vector2 position)
  {
      Ray ray = new Ray(position, Vector3.zero);
      RaycastHit2D hit = Physics2D.GetRayIntersection(ray);

      if (hit)
      {
          if (hit.collider.gameObject.tag == "obstacle")
              return;
      }

      target = position;
}

我无法弄清楚如何仅在特定方向禁用移动,该玩家能够绕过障碍物。

0 个答案:

没有答案