# Problem with 2D Collisions

This topic is 4683 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I seem to be having trouble getting my collsion code to work. I am using the law of conservation of momentum to determine the resultant velocities of the two objects involved in a collision. The problem is when one of the objects possess zero momentum. This object will start to penetrate through the other object which has momentum. I know that the object should start travelling at the same velocity as the object which has momentum. For example when a player hits a moving platform travelling in the opposite direction. The player should travel upwards at the same velocity since the platform has much greater mass. Here is the code that I am using:
FNGE_VECTOR vecNormal = m_SpriteManager.getPlayer()->getCenter() - m_SpriteManager.getMiddleground(m_MiddlegroundID)->getCenter();

vecNormal.Normalize();

// Project the velocities of the player and the middleground object onto the normal.

float fPlayerVelocity = m_SpriteManager.getPlayer()->getVelocity().DotProduct(vecNormal);

float fObjectVelocity = m_SpriteManager.getMiddleground(m_MiddlegroundID)->getVelocity().DotProduct(vecNormal);

float fP = (2.0 * (fPlayerVelocity  - fObjectVelocity)) / (m_SpriteManager.getPlayer()->getMass() + m_SpriteManager.getMiddleground(m_MiddlegroundID)->getMass());

FNGE_VECTOR vecPlayerVelocity = m_SpriteManager.getPlayer()->getVelocity() - (vecNormal * fP * m_SpriteManager.getMiddleground(m_MiddlegroundID)->getMass());
FNGE_VECTOR vecObjectVelocity = m_SpriteManager.getMiddleground(m_MiddlegroundID)->getVelocity() + (vecNormal * fP * m_SpriteManager.getPlayer()->getMass());

m_SpriteManager.getPlayer()->setVelocity(vecPlayerVelocity.x, vecPlayerVelocity.y, vecPlayerVelocity.z);

m_SpriteManager.getMiddleground(m_MiddlegroundID)->setVelocity(vecObjectVelocity.x, vecObjectVelocity.y, vecObjectVelocity.z);



##### Share on other sites
Are you doing elastic or inelastic collisions (or even perfect inelastic)? Either way, it looks like you're setting your momentum (fP) wrong.

• ### What is your GameDev Story?

In 2019 we are celebrating 20 years of GameDev.net! Share your GameDev Story with us.

• 11
• 15
• 11
• 11
• 9
• ### Forum Statistics

• Total Topics
634151
• Total Posts
3015825
×