In my ping pong game, I want it so that every time the ball goes off screen it rewards a point to the appropriate pong and then creates a new ball, but this is not working out. Here are the things that are going wrong:
-
It does not count any points when the ball goes off screen.
-
An Attempt to getLinearVelocity error appears pointing to line 151:
local vx3, vy3 = ball:getLinearVelocity()
This is what I am using to add balls, give points, and remove balls:
local function createBall() ball = display.newCircle(centerX, centerY, 20) physics.addBody(ball, "dynamic") ball:setLinearVelocity(math.random(-400, 400), math.random(-200, 200)) ball.id = "ball" print("ball created") end local function addScore() if (ball.x \< left - 10) then score2 = score2 + 1 score2.text = score2 end if (ball.x \< right + 10) then score1 = score1 + 1 score1.text = score1 end end local function removeBall() if (ball.x \< left - 10) or (ball.x \> right + 10) then addScore() createBall() Runtime:removeEventListener("enterFrame", removeBall) display.remove(ball) print("removed") end end
And here is what I use to detect collisions (globally). The error line is the first line in the function:
local function onCollision(event) local vx3, vy3 = ball:getLinearVelocity() if event.phase == "began" then if ((event.object1.id == "player" and event.object2.id == "ball") or (event.object1.id == "ball" and event.object2.id == "player")) then ball:setLinearVelocity(vx3 \* -1, vy3) end if ((event.object1.id == "enemy" and event.object2.id == "ball") or (event.object1.id == "ball" and event.object2.id == "enemy")) then ball:setLinearVelocity(vx3 \* -1, vy3) end if ((event.object1.id == "topBarrier" and event.object2.id == "ball") or (event.object1.id == "ball" and event.object2.id == "topBarrier")) then ball:setLinearVelocity(vx3, vy3 \* -1) end if ((event.object1.id == "bottomBarrier" and event.object2.id == "ball") or (event.object1.id == "ball" and event.object2.id == "bottomBarrier")) then ball:setLinearVelocity(vx3, vy3 \* -1) end end end
The onCollision function is running on a “collision” eventListener, and the removeBall function is on an enterFrame:
Runtime:addEventListener("enterFrame", removeBall) Runtime:addEventListener("collision", onCollision)
Thank you to the community for the help so far.