访问 Rigidbody2D 的 RaycastHit2D 目标?
accessing Rigidbody2D of RaycastHit2D target?
我已经让我的播放器发出光线投射来检查另一个游戏对象让我们说它是一个盒子,我想访问盒子的 Rigidbody2D 并在我按下一个键时对其施加力。处理这种情况的方法有哪些?您认为哪些方法最有效、最灵活?
这是我目前正在处理的内容。
RaycastHit2D hit = Physics2D.Raycast(new Vector2(transform.position.x, transform.position.y - 0.6f), new Vector2(transform.position.x, transform.position.y - 1.6f));
if(hit.collider != null && Input.GetKey(KeyCode.E))
{
// access gameobject stored to "hit" and AddForce to it's Rigidbody2D??
}
变量hit
是RaycastHit2D. RaycastHit2D has the property of rigidbody
, which returns the Rigidbody2D component of the object that was hit.的类型,所以可以通过hit.rigidbody
访问。
另一种选择是使用 hit.gameObject.GetComponent<Rigidbody2D>()
,但要注意 GetComponent() 调用对性能的影响。
要在该 Rigidbody2D 上添加一个力,您只需提供一个 Vector2 和一个带有 AddForce() method 的可选力模式。 hit.rigidbody.AddForce()
这样就可以了。
此外,您可能需要考虑为您的 Physics2D.Raycast 调用提供正确的起点和方向。您似乎在尝试判断 y 轴上 1 个单位距离内是否有物体。如果是这样,方向应该是 Vector2.up,距离应该是 1.0f,类似于:Physics2D.Raycast(new Vector2(transform.position.x, transform.position.y - 0.6f), Vector2.up, 1.0f)
我已经让我的播放器发出光线投射来检查另一个游戏对象让我们说它是一个盒子,我想访问盒子的 Rigidbody2D 并在我按下一个键时对其施加力。处理这种情况的方法有哪些?您认为哪些方法最有效、最灵活?
这是我目前正在处理的内容。
RaycastHit2D hit = Physics2D.Raycast(new Vector2(transform.position.x, transform.position.y - 0.6f), new Vector2(transform.position.x, transform.position.y - 1.6f));
if(hit.collider != null && Input.GetKey(KeyCode.E))
{
// access gameobject stored to "hit" and AddForce to it's Rigidbody2D??
}
变量hit
是RaycastHit2D. RaycastHit2D has the property of rigidbody
, which returns the Rigidbody2D component of the object that was hit.的类型,所以可以通过hit.rigidbody
访问。
另一种选择是使用 hit.gameObject.GetComponent<Rigidbody2D>()
,但要注意 GetComponent() 调用对性能的影响。
要在该 Rigidbody2D 上添加一个力,您只需提供一个 Vector2 和一个带有 AddForce() method 的可选力模式。 hit.rigidbody.AddForce()
这样就可以了。
此外,您可能需要考虑为您的 Physics2D.Raycast 调用提供正确的起点和方向。您似乎在尝试判断 y 轴上 1 个单位距离内是否有物体。如果是这样,方向应该是 Vector2.up,距离应该是 1.0f,类似于:Physics2D.Raycast(new Vector2(transform.position.x, transform.position.y - 0.6f), Vector2.up, 1.0f)