i'm developing a 2d game in XNA and i'm currently working on my physics class. and my current task is to stop an object when it's colliding with another. i have made my game call this function when ever 2 objects collide:
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 is that instead of stopping. the object that was moving is pushed back by the amount of it's width. can someone please show/tell me how to do this i have been stuck on this for sooo long in many projects.
thanks
You are not putting target's and owner's width and height into calculation. Where is the X,Y of a target/owner? Middle? Left-Top?
If collision is head-to-head then
velocity=sqrt(x_velocity*x_velocity+y_velocity*y_velocity); //some pseudo
public void BlockMovement(gameObject target) {
//you can call width by just typing width. same for height
owner.position.X -=owner.x_velocity*penetration_length/(owner.velocity);
owner.position.Y -=owner.y_velocity*penetration_length/(owner.velocity);
}
//so, if big part of speed is in x-direction then the position will
//change mostly on x-direction and opposite to velocity
If you dont have a velocity variable, you can introduce a position history of 2 iterations back to compute actual velocity direction.