# bounce implementation

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

## Recommended Posts

Hi! What is the best way to implement bouncing having the "ball" position and velocity vector and the position of the 4 vertices of a "wall"? I wrote the following code: - First I calculate the faces normals - I don't know on wich face the "ball" hit the "wall" so I check this using dotproduct between plane and starting position and between plane and current position - Now I need to reorient "ball" velocity vector so that it gives the impression of the bounce, using the normal of the right face. Main queston: HOW TO?
           o          <STARTPOS
v0 .---/-. v1
|  /  |
vN2 <-| o----> vN1    <CURPOS
|  \  |
v2 '---\-' v3
o          <HOW TO?

float dotstart = D3DXPlaneDotCoord(&plane, &pP->startPos);
float dot = D3DXPlaneDotCoord(&plane, &pP->curPos);
[...]

{
// Generate normals in the middle of the plane face
D3DXVECTOR3 vN1, vN2;
D3DXVec3Cross(&vN1, &D3DXVECTOR3(v1-v0), &D3DXVECTOR3(v2-v0));
D3DXVec3Cross(&vN2, &D3DXVECTOR3(v0-v1), &D3DXVECTOR3(v0-v2));
vN1 += D3DXVECTOR3(v2-v0)*0.5f + D3DXVECTOR3(v1-v0)*0.5f;
vN2 += D3DXVECTOR3(v2-v0)*0.5f + D3DXVECTOR3(v1-v0)*0.5f;

// See on which face of the plane the collision occurred
if (dotstart < 0 && dot > 0.f) //  \-> N1
{
// Now how to orient velocity vector ?
}
else if (dotstart > 0 && dot < 0.f) //  <-\ N2
{
// Now how to orient velocity vector ?
}
}

[\source]


##### Share on other sites
To make an perfect elastic bounce, you just have to invert the velocity of the ball in the direction of the normal vector.
The normal is :

D3DXVec3Cross(&vN, &D3DXVECTOR3(v1-v0), &D3DXVECTOR3(v2-v0));

then , if v is the velocity vector of the ball, the new velocity is calculated this way :

nomalize vN so that ||vN||=1
D3DXVec3Dot(&v2,v,vN)
newV = v - 2 * v2

this should work whatever the face the ball is hiting

david

##### Share on other sites
Sounds great! Thank you very much.

• ### What is your GameDev Story?

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

• 14
• 14
• 45
• 22
• 27
• ### Forum Statistics

• Total Topics
634044
• Total Posts
3015210
×