# Ball Ball Collision And Response

### #1 slayer 64

slayer 64

Slayer of gingers

• GMC Member
• 4301 posts
• Version:GM:Studio

Posted 01 September 2009 - 12:28 AM

i wanted to know how to get balls to collide perfectly. i found this post and took what he said and put it into a gmk. the balls collide with each other and bounce off perfectly. you can adjust the radius, mass, and bounce of a ball. bounce is set to 1; less will slow the ball down when it hits another, more will increase its speed. it doesn't use gm built in collision checking. click a ball to make it move towards the mouse.

Host A

here is the collision code.
end step event of obj_ball
```var vaP1,vaP2,dis,va1,vb1,va2,vb2,vp1,vp2,dx,dy,dt;

with obj_ball
{
if id!=other.id
{
dx=other.x-x;
dy=other.y-y;
dis=sqrt(sqr(dx)+sqr(dy));

{
//normalize
dx/=dis;
dy/=dis;

//calculate the component of velocity in the direction
vp1=hspeed*dx+vspeed*dy;
vp2=other.hspeed*dx+other.vspeed*dy;

if (vp1-vp2)!=0
{

//move the balls back so they just touch
x-=hspeed*dt;
y-=vspeed*dt;
other.x-=other.hspeed*dt;
other.y-=other.vspeed*dt;

//projection of the velocities in these axes
va1=(hspeed*dx+vspeed*dy);
vb1=(vspeed*dx-hspeed*dy);
va2=(other.hspeed*dx+other.vspeed*dy);
vb2=(other.vspeed*dx-other.hspeed*dy);

//new velocities in these axes. take into account the mass of each ball.
vaP1=(va1+bounce*(va2-va1))/(1+mass/other.mass);
vaP2=(va2+other.bounce*(va1-va2))/(1+other.mass/mass);

hspeed=vaP1*dx-vb1*dy;
vspeed=vaP1*dy+vb1*dx;
other.hspeed=vaP2*dx-vb2*dy;
other.vspeed=vaP2*dy+vb2*dx;

//we moved the balls back in time, so we need to move them forward
x+=hspeed*dt;
y+=vspeed*dt;
other.x+=other.hspeed*dt;
other.y+=other.vspeed*dt;
}
}
}
}```

Edited by slayer 64, 01 September 2009 - 04:10 PM.

• 1

### #2 Tepi

Tepi

GMC Member

• Global Moderators
• 4248 posts
• Version:GM:Studio

Posted 01 September 2009 - 03:24 PM

Way to go. Now I can just redirect here when someone asks the solution to this problem.

While you're at it, why not make it work with different masses as well? Then elasticity and friction and so on. It'd be a lot easier now that you've got the components already. You could even extend it into 3D from here - there wouldn't be much difference.

P.s. if or when you're going to release more of these scripts, please consider integrating them into one topic. It isn't practical to have another topic for every script about different intersections.
• 0