TransWikia.com

How to prevent a sprite to move in an angle that will lead to collision

Game Development Asked by user3150201 on February 4, 2021

I have two sprites that can move in any angle. The sprites are rectangular.

I created bounding boxes for both the sprites. These boxes rotate whenever the sprite rotates. They always surround the sprite and only the sprite. (Exact fit).

I have succesfully implemented collision detection for the two bounding boxes. I did this by checking wether box1 contains any of the vertices of the box2, and the opposite. (I know this way is not perfect, since it is possible for two rectangles to intersect without having each other’s vertices inside themselves, but for my needs it’s good enough).
So now I know when the two sprites collide.

But I have a problem with reacting when the two sprites collide.

When these sprites collide, I want to prevent them from overlapping each other (any more than a few pixels). In other words, upon collision, I want to allow the sprite to move only in a direction where it won’t go deeper into the other sprite.

As I said, each sprite can move freely in any angle (the game is for two players, each controls a sprite).

EDIT:
To word it differently – Upon collision of two sprites, I need to find out the range of angles a sprite can move, that will allow it to to move out of the collision – this is so I can prevent the user from moving the sprite in any other angle, upon collision.

How can I do that? Thank you for your help

One Answer

Finally found a solution!

This solution isn't perfect, sometimes sprites get a little stuck. But it doesn't involve all the math stuff that people like me struggle with. I'm sharing this because maybe it will help someone.

Everytime I move a sprite, I save it's previous location in a variable. If the sprites collide, I reset it's location to the location it had before the collision. This will take the sprite only a small number of pixels back, so the 'bouncing back' won't be noticable. It will prevent the sprite from overlapping the other sprite.

Thanks for those who tried to help :)

Answered by user3150201 on February 4, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP