Blocking movement in 2d space

C++, C#, Java, PHP, ect...
Post Reply
User avatar
VZdemon
Posts: 93
Joined: Thu Nov 25, 2010 1:55 pm

Blocking movement in 2d space

Post 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. :)
it's VZdaemon on xbox live
User avatar
vitinho444
Posts: 2819
Joined: Mon Mar 21, 2011 4:54 pm

Re: Blocking movement in 2d space

Post 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..
My Company Website: http://www.oryzhon.com

Skype: vpegas1234
User avatar
Callan S.
Posts: 2042
Joined: Sun Jan 24, 2010 5:43 am

Re: Blocking movement in 2d space

Post 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.
User avatar
Nihilant
Posts: 47
Joined: Wed Aug 31, 2011 8:24 pm

Re: Blocking movement in 2d space

Post 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.
Post Reply

Return to “Coding”