Game Development Reference
In-Depth Information
Figure 4-4. The game running in the console
Moving a Character
In any 2D game, you are in control of a character, and this character moves on the screen as you tap
or swipe the screen of the mobile device. Let's examine the code that makes the character move.
The screen is a grid that has two dimensions: height and width. Most screens start with (0,0) being
the top-left corner of the screen, with a positive x value indicating that the character is to the right
from the origin and a negative value indicating that the character is to the left of the origin. Similarly,
a positive y indicates that the character is below the origin and a negative y indicates that the
character is above it. Using this information, we can safely deduce that to move a character to the
right, we need to add a positive increment to the x-coordinate, and to move the character to the left,
we add a negative increment to the x-coordinate.
Let's create the structure for our character as a table structure like a point that will hold the x and y
position of the character:
local point={x=0,y=0}
-- Initialize the point structure with x and y as 0
Now let's move the character 5 units to the right:
local i
for i=1,5 do
point.x=point.x+1
end
 
Search WWH ::




Custom Search