Public Group

Maths problem

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

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 on other sites
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 on other sites
Doh! Silly mistake :P thats done the job, works perfectly now, thanks!

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.

1. 1
2. 2
Rutin
19
3. 3
4. 4
5. 5

• 15
• 13
• 9
• 12
• 10
• Forum Statistics

• Total Topics
631442
• Total Posts
3000091
×