Jump to content
  • Advertisement
Sign in to follow this  
jkh13

Maths problem

This topic is 3078 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi I am programming using xna and c# and I have a maths problem that has been bugging me for some time.

I have a location position vector and a rotation angle in radians. I want to be able to move the position vector by 1 unit in the rotation direction. So for instance if the rotation is PI/2 and the position is (0,0) the new position is now (0,-1) as the rotation is facing downwards so it moves 1 unit down.

At the moment I have tried using a rotation matrix to get the correct new location:

Vector2 t = new Vector2(1,0);
t.X = (float)(t.X * Math.Cos(rotation) - t.Y * Math.Sin(rotation));
t.Y = (float)(t.X * Math.Sin(rotation) + t.Y * Math.Cos(rotation));
location += t;

I am seeing some really odd behaviour though. It seems it works with some directions but fails with others.

[Edited by - jkh13 on July 12, 2010 6:21:08 PM]

Share this post


Link to post
Share on other sites
Advertisement
You've made the classic error here: you're overwriting t.X in the first line, and then using the *new* value in the second line (when it should be the original value).

Anyway, since you're just rotating the vector (1,0), you can reduce this to:
Vector2 t(Math.Cos(rotation), Math.Sin(rotation));

			
		

Share this post


Link to post
Share on other sites
I've made that mistake myself at least five times over the years. In my defense, it did take me less and less time to realize what the problem was. :)

With the coding style I have develop over the last few years, this type of mistake is virtually impossible, so I'll explain one rule that might help you:
"Whenever possible, declare a variable as late as possible, give it a descriptive name, assign its value when its constructed, and never change it."

I sometimes make these variables `const', but perhaps this ends up getting in the way of readability, so I am not going to advocate doing it.

Of course there are variables whose value changes in each iteration of a loop, or cases where following this rule would result in unclear code, so use common sense.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!