0
\$\begingroup\$

Provided that both objects have rectangular hitboxes, x and y positions and height/width, what is the best way to check if a moving 2D object will collide with another immobile one before reaching its destination?

No engine is being used.

\$\endgroup\$

2 Answers 2

0
\$\begingroup\$

If the other thing isn't moving, you can use a raycast. (You didn't say what engine you're working with, but there should be a way to use one for any major engine.) Start at a point just outside of your moving object's hitbox, and cast a ray in the direction of the object's movement, with its length being the length the object will move in however much time you want to "predict." If the ray hits the immobile object, then that's your predicted collision. If not, your path is clear for the length of the ray.

\$\endgroup\$
3
  • \$\begingroup\$ I'm not using an engine, but I think I can try to implement that. \$\endgroup\$ Commented Jan 5, 2021 at 0:00
  • \$\begingroup\$ If you're building your own system, and it's in 2D, look up "Bresenham's line algorithm" for a simple way to calculate the pixels on the 2D grid that your ray will touch. \$\endgroup\$ Commented Jan 5, 2021 at 0:12
  • 2
    \$\begingroup\$ Fun fact: you can expand the second box by the dimensions of the first box, and fire your ray against the expanded version - that will correctly detect when the two boxes will touch (taking into account the size of the first one), even if the center point raycast misses the original second box. You can even use the relative velocity of both rectangles as your ray direction to do collision detection where both boxes are in motion at once. \$\endgroup\$
    – DMGregory
    Commented Jan 5, 2021 at 0:14
0
\$\begingroup\$

This question is from seventeen months ago so I'm not going to get too deep into it.

Assuming this is some kind of object-avoidance problem, I would suggest that you could just add the "radius" of the stationary object to the "radius" of the moving object then check to see if the centre-line path of your moving object falls within that distance of the stationary object. The actual likelihood of the two objects colliding would depend largely on the aspect ratios of the two hit boxes; the further the aspect ratio is from 1 for either object, the less accurate this method becomes, but should provide a close-enough idea of the likelihood of collision for purposes of object avoidance, if that's the goal.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .