So I am making a game like pong in Corona and I am stuck at how to get the paddles to trace the ball. I have defined the ball's x coordinate as ball.x = ballx
and ballx = 160
but when I use
local myListener = function( event )
upperpad.x = ballx
lowerpad.x = ballx
end
Runtime:addEventListener( "enterFrame", myListener )
to keep the paddles x value updated to the ball's x value, it stays constant. How can I express ballx
as a changing value and get the paddles to mirror the ball's x value?
The ballx value stays constant because you're probably not updating it, and changing directly ball.x instead. Indeed, this is the way to do it: you should use ball.x as this is is the real value that's being changed, and not ballx.
Yet, if you still want to use a reference value to ball.x, you can set ballx = ball.x
and then update the ballx value directly.
When you're done updating the ballx value, you can update the ball.x value as well, and the paddles just like you did.
local updateBall = function()
ballx = ballx + 20 --update the ballx value
end
Runtime:addEventListener("enterFrame", updateBall)
local myListener = function(event)
ball.x = ballx --then update the ball itself with the ballx value
upperpad.x = ballx --and make the paddles follow
lowerpad.x = ballx
end
Runtime:addEventListener("enterFrame", myListener)
EDIT: If you want to manually set the paddles' position depending on the ball's (which is handled by the physics engine), simply make them follow the original ball.x value. You don't need ballx.
local movePaddles = function(event)
upperpad.x = ball.x
lowerpad.x = ball.x
end
Runtime:addEventListener("enterFrame", movePaddles)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.