尝试在 Unity 中使用光线投射 (2D) 拾取与玩家位置相关的对象(如果该对象靠近玩家位置)

Attempting to pick up an object that is relative to a player's position if it's near it using raycast (2D) in Unity

所以,我是一周前开始接触 C# 和一般编程的新手。我一直在研究 2D 的光线投射,我想让一个物体在玩家靠近它时被移除,然后我按下 'E' 键,这将在我拿起武器时使用。

这工作正常,但是,基本上只有当我将鼠标放在对象上时它才有效。我不完全想要这个,我想要它到我靠近对象的地方,然后我按 'E',它会删除它。像一个范围的东西。

这是我当前的脚本:

    void Update()
    {

        Vector2 worldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        RaycastHit2D hit = Physics2D.Raycast(worldPoint, Vector2.zero);

        if (hit.collider != null && Input.GetKey(KeyCode.E))
        {
            Debug.Log(hit.collider.name);
            Destroy(hit.collider.gameObject);
        }
    }
}

任何帮助都会很棒,谢谢。

尝试研究使用 2D 播放器位置而不是光线投射。我知道每当我这样做时,我都会使用玩家对撞机并检查对象是否已进入。

Pseudo code could be something like this:
- Add collider set as trigger to your pickup
- Add some Pickup script to your pickup GameObject, it will hold the bullets count etc.
- When your player walks into a trigger, try to get pickup component from other object it collided with to see if it was a pickup.
- If it was, it has the Pickup component.
- Take the bullets count and add it to your player's weapon / bag / inventory
- Remove the pickup from scene

逻辑有点错误。这是函数 Physics2D.Raycast.

的文档

我假设您正在尝试用鼠标指示相对于玩家的方向,因此代码将如下所示:

var hit = Physics2D.Raycast(
     playerTransform.position,  // start raycasting from players position
     worldPoint - playerTransform.position  // in the direction of where the mouse is
     );

// some debugging code which will be excluded from build because of this condition 
# if UNITY_EDITOR
Debug.DrawLine(
     playerTransform.position, // start point same as ray
     (worldPoint - playerTransform.position) * 10 + playerTransform.position,  // end point = direction from start point * distance + start point
     Color.white,  // color of ray
     Time.deltaTime // duration
     );
#endif

也使用Debug.DrawLine to see how the ray is being cast. If it's on the object but not colliding check Z-depth and layer mask. Maybe it's worth checking out some tutorials