- Home /
How to boxcast where a dynamic rigidbody2D's box collider will be in the next frame?
Essentially I'm trying to boxcast (Physics2D.BoxCastAll, in FixedUpdate) a dynamic rigidbody2D's box collider one frame ahead of where the rigidbody2D will end up (to see what it will collide with in the next frame, if the boxcast hits something). I'm using the velocity, scaled down by * Time.fixedDeltaTime, but currently the boxcast is much farther out than I would expect, a distance/magnitude too big.
Here's a crude drawing of what seems to be happening.
private Rigidbody2D rb2d;
private BoxCollider2D bc;
private RaycastHit2D[] cast;
// Use this for initialization
void Start () {
rb2d = GetComponent<Rigidbody2D>();
bc = GetComponent<BoxCollider2D>();
cast = new RaycastHit2D[5];
}
// Update is called once per frame
void FixedUpdate () {
if (!rb2d.isKinematic)
{
cast = Physics2D.BoxCastAll(rb2d.position, bc.size, rb2d.rotation, rb2d.velocity * Time.fixedDeltaTime);
//Debug.Log(rb2d.position + ", " + (rb2d.position + (rb2d.velocity * Time.fixedDeltaTime)));
//Debug.DrawRay(rb2d.position, Vector2.up, Color.white); //rb2d.position + (rb2d.velocity * Time.fixedDeltaTime)
//Debug.DrawRay(rb2d.position + (rb2d.velocity * Time.fixedDeltaTime), rb2d.velocity * Time.fixedDeltaTime, Color.magenta);
if (cast.Length > 0)
{
foreach (RaycastHit2D tran in cast)
{
Debug.Log(tran.collider.gameObject);
}
}
}
}
Thanks for any help.
whats the
rb2d.velocity * Time.fixedDeltaTime
for? the box gets casted in
rb2d.position
edit: I may be wanting to use the position of the box collider (bounds.center) as a origin point instead, and perhaps use an Overlap method instead
that's the direction of the cast. I wasn't sure if the origin should include the velocity's "extra" magnitude (something like "rb2d.position + rb2d.velocity * Time.fixedDeltaTime" for the origin), or if that would be calculated with the distance.
would I want nothing for the direction, Vector2.zero? I just want to cast at the boxcollider2D's current position + the slight extra velocity (presumably "+ (rb2d.velocity * Time.fixedDeltaTime)"), to see what the collider will hit in the next frame.
Answer by xxmariofer · Dec 23, 2020 at 08:40 AM
Ok; I think i have just understood your issue, it was driving me crazy because to my understanding a direction made no sense there, we were confusing Physics2D.BoxCast, that its similar to Physics.RayCast but with a "bigger" ray with Physics2D.OverlapBox, here is the documentation
https://docs.unity3d.com/ScriptReference/Physics2D.OverlapBox.html