Moving graphics with trigonometry

Mar 28, 2009 21:38

http://bojordan.com/log/?p=691
Notice: This is intended to involve only very basic concepts.

No matter the scope, most “game” programming these days involves moving pictures around on a computer screen, and performing this task can be very easy with a little basic math (specifically, trigonometry). Small two-dimensional graphics in games are usually called “sprites”, and in this exercise we’ll simply move a sprite.

We will be plotting a trajectory of a sprite across our screen, and to do this we keep track of
  1. the sprite’s position (a single point containing its X and Y coordinates),
  2. a velocity,
  3. and an angle at which to plot the distance the sprite travels.

Our game will draw the sprite to the screen as fast as it can, and we will know how much time has elapsed since the last time we drew the sprite. So, we will be provided the final number we need to plot our new sprite position: elapsed time.
We are calculating a distance vector, which is basically a line from one point to another. If our sprite’s velocity is five pixels per second, and one second elapses, it will travel a distance of five pixels. However, what is the new X,Y position of that point? It depends on the angle!

To calculate the amount along the X and Y axes our sprite has traveled, perform two simple calculations:

distanceX = velocity * elapsedTime * cos(angle); distanceY = velocity * elapsedTime * sin(angle);

Add these values to the previous X,Y position of the sprite and you’ll have the new position of the sprite. The diagram assumes a starting position of (1,1), and shows two distance vectors: The red is with an angle of π/4 radians (or 45º from vertical), while the green is an angle of π/2 radians (or 90º from vertical). Both have the same velocity magnitude.

To add a little simple rebound off the sides of the screen, make sure that the X and Y coordinates of the sprite are not beyond the edges. For a screen 800×600 pixels, where directly up is an angle of 0, simple reverse the angle when the sprite goes off the left or right of the screen, and subtract the angle from PI when it goes off the top or bottom.

if (xPosition > 800) { xPosition = 800; angle = -angle; } if (xPosition < 0) { xPosition = 0; angle = -angle; } if (yPosition > 600) { yPosition = 600; angle = PI - angle; } if (yPosition < 0) { yPosition = 0; angle = PI - angle; }
To slow the sprite down at a certain rate of deceleration, simply subtract from the velocity an amount that is multiplied by the elapsed time:

velocity = velocity - (deceleration * elapsedTime);
This isn’t the most accurate of physics demonstrations, but surprisingly advanced games can be built around calculations as simple as these.

Next we’ll discuss how to derive a distance from two points, and soon go over some handy linear interpolation.
Previous post
Up