• XNA Doesn't agree with my math
    11 replies, posted
I'm trying to make a top down game in XNA, where you fly around in a little spaceship and shoot stuff.. The aiming system is such that the ship turns to aim toward your mouse. I got a similar thing working on a different game, but the exact same code didn't work for this. [code]double O = Ship.Position.X - mouse.X; double A = Ship.Position.Y - mouse.Y; Ship.Rotation = (float)Math.Atan2(O, A);[/code] I've tried many variations on this code, I just don't understand why it doesn't aim at my mouse properly.
Atan2 takes y,x not x,y as you have it.
Damn, idiot mistake D: Changing... -EDIT- Ok, so I fixed that, as well as adding an offset to get the "real" centre of the ship [code]double O = (Ship.Position.Y + Ship.Centre.Y) - mouse.Y; double A = (Ship.Position.X + Ship.Centre.X) - mouse.X; Ship.Rotation = (float)Math.Atan2(O, A);[/code] Still isn't working as it should. I've tried swapping the Ship.Position.Y - Mouse.Y with Mouse.Y - Ship.Position.Y, same with X, but no difference. I honestly have no idea why this doesn't work; but I can tell it's a really stupid mistake.
What exactly "isn't working"?
Math.Atan2 returns in radians. Do you perhaps require a degree?
nullsquared: It's kinda hard to explain; but the ship is rotating, just in no real relation to the mouse position. For example, if I move the mouse from left to right across my screen, the ship starts off pointing at something like 45 degrees, goes towards 90 degrees, then goes back to 45 again. If you need more info, I'll make a quick video of it to demonstrate. Senney: Nope, I have everything working in radians. I thought maybe that was it to start with, but it's not :/
Step through it with a debugger and work out the maths yourself with a calculator. You should be able to spot where the numbers start to go wrong.
[QUOTE=Senney;20755900]Math.Atan2 returns in radians. Do you perhaps require a degree?[/QUOTE] ^ this
Random thoughts: -Does Math.Atan2() require its input to be unit length ? -Or does your Ship.Rotation not support negative rotation / rotation wrapping ?
Try "mouse.* - Ship.Position*". I always remember it as "target - source". Seen as the mouse is the 'target' of the ship, this should apply.
I don't know how you rotate the ship sprite but, try to transform the angle into 0-360 instead of -180 to 180 pseudo code [code] angle = Atan2(y, x); if (angle < 0) angle += 360 [/code] and if in radiant, use 2*PI as 360.
For all the suggestions about negative angles and such, I'll have to look in further detail. Thing is, this EXACT same game (apart from a different name (cannon instead of ship)) worked perfectly. It's really quite odd. I'm going to try stepping through the code like yngndrw suggested
Sorry, you need to Log In to post a reply to this thread.