It looks like you're new here. If you want to get involved, click one of these buttons!

Hi all! I have been having trouble with the physics in my air hockey game. The problem is that the collision detection I programmed splits the puck into 4 parts and therefore if the player hits the puck straight on it won't go straight, it will deflect at an angle. P.S. the "speed" that I talk about in my code comments and that is in the code as the variable p_speedX and p_speedY is just moving it at a certain speed either forward (positive) or backwards (negative).

Here is the collision detection code:

```
--collision detection
if math.sqrt((p_ball.x-r_ball.x)^2+(p_ball.y-r_ball.y)^2) <= p_ball.radius+r_ball.radius then
if r_ball.x<p_ball.x then
p_speedX=math.sqrt((p_speedX)^2)+0.1-- makes speed positive and faster
end
if r_ball.x>p_ball.x then
p_speedX=((math.sqrt((p_speedX)^2))*-1)-0.1--makes speed negative and faster
end
if r_ball.y<p_ball.y then
p_speedY=math.sqrt((p_speedY)^2)+0.1--making speed positive then faster
end
if r_ball.y>p_ball.y then
p_speedY=((math.sqrt((p_speedY)^2))*-1)-0.1--making speed negative then faster
end
end
if math.sqrt((p_ball.x-l_ball.x)^2+(p_ball.y-l_ball.y)^2) <= p_ball.radius+l_ball.radius then
if l_ball.x<p_ball.x then
p_speedX=math.sqrt((p_speedX)^2)+0.1-- makes speed positive and faster
end
if l_ball.x>p_ball.x then
p_speedX=((math.sqrt((p_speedX)^2))*-1)-0.1--makes speed negative and faster
end
if l_ball.y<p_ball.y then
p_speedY=math.sqrt((p_speedY)^2)+0.1--making speed positive then faster
end
if l_ball.y>p_ball.y then
p_speedY=((math.sqrt((p_speedY)^2))*-1)-0.1--making speed negative then faster
end
end
```

Thank you!

Tagged:

## Comments

First, I suggest you use

`p_ball:dist(r_ball)`

to get the distance between the two balls.math.sqrt((p_speedX)^2) leaves p_speedX unchanged, ie why bother?

You should use physics in your game, it makes things much easier. Have a look here

https://coolcodea.wordpress.com/2013/07/

especially post #91