March 29th, 2009

Rotation controlled direction using trigonometry and radians in Silverlight

All Silverlight Examples, Silverlight 2 tutorials, Silverlight C# Tutorials, Silverllight Games, by Gavin Wignall.

The below example shows an object being controlled by user input. To get the object to turn left or right is a relatively simple procedure as seen below:

if (e.Key == Key.Left)
{
tankRotate.Angle -= 1;
}
if (e.Key == Key.Right)
{
tankRotate.Angle += 1;
}


The above example turns the object by 1 degree left or 1 degree right, you can use any value to make the object turn faster or slower.

To get the object to move forward in the direction it is facing is going to require our old friend ‘Trig’ to take center stage. We can use the following formulae to calculate how far to move our object by its X and Y co-ordinates:

Move X by: Math.Cos(Angle) * Speed

Move Y by: Math.Sin(Angle) * Speed

Where Angle is in radians.

Radians

1 radian is equal to 57.29577 degrees of a full circle. So if our object is turned at an angle of 57.29577 degrees it is equal to 1 radian. To work out the value of our angle in radians we can use the following formula:

Radians = Angle / 360 * 2 * Pi

Working out how much to move our object

i.e. if our object is turned to 45 degrees and our required movement speed is 2.

X += Math.Cos(45 / 360 * 2 * 3.14159) * 2;

Y += Math.Sin(45 / 360 * 2 * 3.14159) * 2;

Applying this formula to the C#

So to return to the example at the begining of this post. I use the below calculations to work out how much to increase or decrease the X and Y positions of my object:

if (e.Key == Key.Up) 

{

        tankMovement.X += Math.Cos(tankRotate.Angle / 360 * 2 * 3.14159) * 1;

        tankMovement.Y += Math.Sin(tankRotate.Angle / 360 * 2 * 3.14159) * 1;

}

Get the code

Feel free to grab the code here and start playing!

Back Top

Responses to “Rotation controlled direction using trigonometry and radians in Silverlight”

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Back Top