Hi, I'm getting my feet wet in the Playdate SDK and having trouble making a simple Pong clone.
I'm trying to write a general collision detection system for the ball / puck and struggling with the moveWithCollisions
function. Here's a demo of what happens with the current solution.
Here's my code for now, the main focus being the update
callback:
function Puck:init(x, y, speed)
local image = gfx.image.new(10, 10)
gfx.pushContext(image)
gfx.fillCircleInRect(0, 0, image:getSize())
gfx.popContext()
self:setImage(image)
self:setCollideRect(0, 0, self:getSize())
self:setGroups(puck_coll_group)
self:setCollidesWithGroups({bound_coll_group, paddle_coll_group})
self:add()
self:moveTo(x,y)
self.speed = speed
-- determines where to "serve" the puck
math.randomseed(pd.getSecondsSinceEpoch())
local angle = math.random(0, 360)
local v_x = math.sin(math.rad(angle))
local v_y = math.cos(math.rad(angle))
self.velocity = geo.vector2D.new(v_x, v_y):normalized() * self.speed
end
function Puck:collisionResponse()
return "bounce"
end
function Puck:update()
local next_x = self.x + self.velocity.x
local next_y = self.y + self.velocity.y
local actual_x, actual_y, collisions, length = self:moveWithCollisions(next_x, next_y)
if length > 0 then
for index, collision in ipairs(collisions) do
local bounce_vector = geo.vector2D.new(actual_x - collision['bounce'].x, actual_y - collision['bounce'].y):normalized()
self.velocity = bounce_vector * self.speed
end
end
end
What I've written is the fifth or sixth solution I've tried. It seems the most simple and intuitive to me personally. My trig is a little rusty to say the least though.
My thought here would be something like:
- Puck is going to bounce off the wall
- 'bounce' point from the collision table is going to tell me where it'll bounce.
- The vector between the collision, and the point where it will bounce, will be the new velocity vector of the puck (once normalized).
My confusion here lies in: does the 'bounce' collision type "know" about this kind of directional bouncing? Is it doing the math like this StackOverflow solution does? I tried implementing this particular solution, but I'll admit I'm a bit confused, and had no such luck.
It doesn't help that I'm without a lot of the debugging solutions that I would ordinarily have. If anybody has tips for that too, I'd be glad to hear it.
FWIW, I'm developing on Mac.