所以,我一般在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);
}
}
}
任何帮助都会很棒,谢谢。
答案 0 :(得分:0)
尝试使用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
答案 1 :(得分:0)
逻辑上有一点错误。这是函数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
查看射线的投射方式。如果在物体上但没有碰撞,请检查Z深度和图层蒙版。也许也值得一试tutorials。