Game Development Reference
In-Depth Information
increasing in the x will now start to decrease. When the ball hits the bottom of the screen, speed.y
is changed to a negative value, which will make the ball move upward till the ball reaches 0 on the
x-axis, where the speed will once again be negated and the ball will start to move to the right again.
We also have a function called positionBall , which currently just prints the coordinates to the
screen; later on we'll get the ball to display on the screen as well.
Determining the Distance of a Character from an Object
Often, you'll need to know the distance between the player character and a particular object on the
screen. You may also need to know the angle at which the object is to the player.
Let's say we want the player character to turn and look at the object, so we need to know the distance
and the angle between these. Once again, math will come to the rescue—trigonometry, to be precise.
For this, we'll use the help of the Pythagorean theorem. To recap what it is, according to Wikipedia,
it states, “In any right triangle, the area of the square whose side is the hypotenuse (the side opposite
the right angle) is equal to the sum of the areas of the squares whose sides are the two legs (the two
sides that meet at a right angle)” (see http://en.wikipedia.org/wiki/Pythagorean_theorem ) .
The theorem can be written as the equation a 2 + b 2 = c 2 .
If the player character is at point a and the object that we want to calculate the distance for at point
b, we can use the Pythagorean theorem for calculating. Point a provides us with x1,y1, and point b
provides us with x2,y2.
If we draw a line extending on the x-axis from the player character and a line extending on the y-axis
from the object, we can find that these two lines meet at a common point, forming a right angle.
Now we can apply the Pythagorean theorem to find the hypotenuse, which incidentally is also the
distance between the two points.
We could represent this in code as
local dx, dy=math.abs(object.x - player.x), math.abs(object.y - player.y)
local distance=math.sqrt(dx*dx+dy*dy)
To get the angle between these two points, we need to get atan2 , as follows:
local angle=math.deg(math.atan2(player.y - object.y, player.x-object.x))
There might be a situation when you want to check if the player is in a special area, or if the player
touched a specific area on the screen. The best way to determine that would be to check if the point
is in that rectangle. In simpler words, each point on the screen is a combination of two values, the
x and the y. A rectangle is made up of either two points—a start point and an endpoint—or a start
point and attributes such as width and height (see Figure 4-5 ).
Search WWH ::




Custom Search