Page 1 of 1

Blocking movement in 2d space

Posted: Fri Sep 07, 2012 9:10 am
by VZdemon
Hi, this is a problem that has been troubling me for a long time and when there is no where else to turn i come here. so it sounds really simple but i just can't get it right so can someone please show/tell me how to block an objects movement when it's colliding with another object.

here is what i have so far:(it's in C#)

Code: Select all

public void BlockMovement(gameObject target) {
    //you can call width by just typing width. same for height
    owner.position.X += (owner.position.X - target.position.X);
    owner.position.Y += (owner.position.Y - target.position.Y);
}
the problem with this code is that it pushes the object that's colliding away by the amount of it's width.

thanks for reading. :)

Re: Blocking movement in 2d space

Posted: Fri Sep 07, 2012 1:07 pm
by vitinho444
I dont know much of C#.

But the basic of 2d blocking, its that you want to check if the x+width and y + height faces of the player, are bigger than the block.x and the block .y.
If yes then collision is true and you need to push your player behind. Sorry if im not helping you that much..

Re: Blocking movement in 2d space

Posted: Fri Sep 07, 2012 10:23 pm
by Callan S.
Yeah, when I've tried to manually code collision detection it's always been hard. I found the direction of movement makes it ambiguous as well - if square A overlaps the top right corner of square B, making A flush with the top of B doesn't work if it came into contact via a horizontal movement.

Re: Blocking movement in 2d space

Posted: Mon Sep 10, 2012 10:48 pm
by Nihilant
Are you using rotation of the object that's moving? Or is it just changing x/y coords without actual rotation involved?

If you're using rotation, you need not only to block the movement but also allow for turning (rotating) away from the target object. Anyway, with 2d coordinate system, I'd suggest getting the actual distance between the objects (good ole Pythagorean theorem). Then, if distance is higher than some set value, allow function Move (or set movability to true, whatever), and if it's not - disallow Move. If there's turning/rotating, a player will still be able to turn away from the object he's colliding with and get away. If there's no rotation involved, I guess it can do the trick to check the destination location before moving there: if the destination location is lower than the set value for shortest distance between objects, do not allow the move.

Of course, I'm speaking abstractly but hope it helps at least a bit.