Unity raycast关注游戏对象C#

时间:2018-01-07 00:05:41

标签: c# unity3d raycasting

你好,所以我想让我的光线投射跟随它击中的游戏对象,所以我可以设置我的vector3 FollowTarget所以vector3将离开跟随游戏对象移动私有虚空的光线投射

MoveSelectedToCursorPosition()
    {
        RaycastHit raycastHit;
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, out raycastHit, 1000.0f))
        {
            if(raycastHit.collider.tag == "Terrain")
            {
                gameController.UnitSelection.MoveSelectionToPosition(raycastHit.point);
            }


            if(raycastHit.collider.tag == "Minion")
            {           
                FollowTarget = raycastHit.point;
                gameController.UnitSelection.MoveSelectionToPosition(FollowTarget);

            }
        }
    }

1 个答案:

答案 0 :(得分:0)

光线投射-跟随

Raycast无法做任何事情。它是一个瞬间事件,它在太空中的2个给定点上投射光线。

解决方案

作为评论中提到的Draco18s,您只需保存对转换的引用并使用转换位置。

public class Example {
  private Transform _followTarget;

  MoveSelectedToCursorPosition() {
    RaycastHit raycastHit;
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    if (Physics.Raycast(ray, out raycastHit, 1000.0f)) {
      if (raycastHit.collider.tag == "Terrain") {
        gameController.UnitSelection.MoveSelectionToPosition(raycastHit.point);
      }


      if (raycastHit.collider.tag == "Minion") {
        this._followTarget = raycastHit.collider.transform;
      gameController.UnitSelection.MoveSelectionToPosition(this._followTarget.position);
      }
    }
  }
}