I’ve been trying for a bit but I’ve never implemented something like this before so I honestly have no clue what the best way to implement it is.
I’ve looked around for a few ways to do this but a lot of info features the use of velocity and using that to make a “bounce off” effect which isn’t ideal for me as I’m not using any sort of velocity variable. All I simply would like if for the object to halt when colliding with another. I mean if it’s required then I’ll just have to implement one but if I could get around it then that’d be great.
I was wondering if anyone knew of a good algorithm for this?
Possibly a dumb question, but could you not just set velocity to 0?
So I am guessing you are not implmenting any physics and you are translating your object until it collides, in some cases, you are ending up with an overlap?
Either, once overlap had occured, find the distance of overlap and move your object back by that delta, or prior to colision check, see what the distance is to your target, if it would result in an overlap, set your object position.
hmm, could be another tutorial in this for my page
Exactly that! I’ve been trying to find the distance of the overlap once an collision has happened but I honestly am not sure how to do it. I assumed it’d be as simple as getting the distance between the two objects that are colliding, and then moving the object back by the length of the vector but that doesn’t work since the length is bigger when there is less of an overlap since they’re further away from each other
Ill see if i can get time and do a simple sample, might not be 100% what you need, but it will be something
I have knocked up a quick sample of one way this can be solved, I have put it in my git repo here.
I can move the red and blue sprites, and they will never intersect either each other or the gold box. I am using Rectangles to check for collision.
Hope this helps.
I will probably add this to my list of turorials that I will be posting on my Patreon site here.
The simplest implementation is to do this iteratively. If your game is fixed timestep and things move in units of no more than one screen pixel per frame, then its pretty trivial. If they move faster than that, or your game is not fixed timestep, then you can just break the movement down into smaller steps.
That said, solving the problem with geometry is a pretty fun exercise IMO.
You have a starting position and ending position of the rectangle which is in motion and is interpenetrating with another at the end position. The vector from start to end position is the motion vector. If you negate it and normalize, that is the collision normal. Solve for: what distance along the collision normal must you move back the rectangle to not be in collision?