Game Development Reference
In-Depth Information
This can also be used to increment the position one pixel a time. However, in the preceding example,
we could have also used point.x = point.x + 5 , like so:
print(point.x, point.y)
We do not see anything on the screen as yet, as we have not written any code to display anything. Some
might feel this to be a rather boring method, but if you look at it in the larger scheme of things, you
shall find that if you can get this code working perfectly fine, you can use it with any framework and
language. This shall help you keep your code as modular and portable as possible.
Going Offscreen
={x=0,y=0}
={x=1,y=1}
local dimensions={0,0,320,480}
function positionBall(thePoint)
print("ball is at" .. thePoint.x .. " , ".. thePoint.y)
end
function moveBall()
local newX, newY=point.x+speed.x, point.y+speed.y
if newX>dimensions[3] or newX<dimensions[0] then speed.x = − speed.x end
if newY>dimensions[4] or newY<dimensions[1] then speed.y = − speed.y end
point.x=point.x+speed.x
point.y=point.y+speed.y
end
-- When run, this will get into an infinite loop
while true do
positionBall(point)
moveBall()
end
Here's how it works. The structure point and speed hold the values that tell which direction the ball
should move. To start with, these are both 1, so the ball starting from the top left moves toward the
bottom right diagonally; however, since the width of the screen is less than the height (in portrait
mode), the ball reaches the side before it reaches the bottom of the screen.
newX and newY are the current position and the speed. If these values are greater than the confining
box, then the speed value is negated, so the ball begins moving in the opposite direction. What was
Search WWH ::




Custom Search