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