How to properly bounce this ball

I am trying to figure out how to bounce this pong-like ball off a player’s paddle. The code works fine for the stationary walls, but breaks apart when you try to move into the ball. Below is a video demonstrating this issue.

I have tried other ways of bouncing the ball off surfaces, but all of them have either been too complicated, or simply haven’t worked. I’ve also tried using a loop to move the ball constantly until it is no longer colliding with anything, but this makes the ball movement act weird, making the situation worse.

This is my current script.

local ball = workspace.Ball

local speedX = 0.1
local speedZ = 0.1

local function colliding()
	local parts = workspace:GetPartsInPart(ball)
	if parts[1] then
		return true
	else
		return false
	end
end

while true do
	
	ball.Position += Vector3.new(speedX, 0, 0)
	
	if colliding() then
		speedX = 0 - speedX
		
		ball.Position += Vector3.new(speedX, 0, 0)
		
		print("x")
	end
	
	ball.Position += Vector3.new(0, 0, speedZ)
	
	if colliding() then
		speedZ = 0 - speedZ
		
		ball.Position += Vector3.new(0, 0, speedZ)
		
		print("z")
	end
	
	task.wait()
end

Have you tried turning .canCollide on for the paddle? Might sound dumb but give it a try.

local function colliding()
	local parts = workspace.Ball:GetTouchingParts()
	if #parts > 0 and not table.find(parts, workspace.Baseplate) then
		return true
	else
		return false
	end
end
1 Like

How exactly does this change anything? This is quite literally the same function but using GetTouchingParts()

2 Likes

Sometimes functions that should have the same functionality are not the same. Maybe just try it out, and see if it works. (The functions are probably written another way than the other one)

This does help by not being able to move inside the ball, but you can still move against it to freeze it in place.

This does not really change anything, and i should probably mention that the ball is anchored and hovering above the baseplate, so its not using physics to move.

1 Like

Okay so I probably understand what is going on here, I think the paddle collides with two sides of the ball and thus the ball doesn’t really know where to go, therefore the balls freezes and when not touched goes in the last direction. I could be wrong, but this is my theory.

Yes, the issue is that by moving towards the ball you get it stuck inside the paddle, which makes the ball detect a collision changing its direction, but because it is still inside the paddle, this process repeats indefinitely not letting it move anywhere. This is the problem and i am asking for help as to how to fix it.

Has the ball collisions enabled?

You could use raycasting as an alternative collision detection technique. This could solve the issue if the ball get’s stuck inside as raycasts cannot hit a part if the origin starts from inside the part.

The d normal of the ray should equal to the velocity of the ball which is the Vector3.new(speedX,0,speedZ)