0

I'm doing a (probably simple) task, in which i want to make a drawed object move to a user-controlled (drawed too). All i have is the players X and Y coördinate, defined as respectively Xp and Yp. The object that has to move (after trigger, not included in code down here) to the 'player-object' has its coördinates defined in this.X and this.Y.

        int xDirection = Xp - this.X;
        int yDirection = Yp - this.Y;
        int angleInDegrees = (int)Math.Atan2(xDirection, yDirection);
        double radians = (Math.PI / 180) * angleInDegrees;
        double xTmp = 3 * Math.Cos(radians);
        int xSpeed = (int)xTmp;
        double yTmp = 3 * Math.Sin(radians);
        int ySpeed = (int)yTmp;
        Console.WriteLine(xDirection);
        Console.WriteLine(yDirection);
        Console.WriteLine(xSpeed);
        Console.WriteLine(ySpeed);
        Console.ReadLine();

This doesn't give me the right figures, so i was wondering what may be wrong.

The toughest bit about this probably the fact that the object that has to move to the playerobject may be approached from all the sides (360 degrees) but there's no angle of approach available.

I hope to be complete with my question, Tim

Machavity
  • 30,841
  • 27
  • 92
  • 100
Tim Lagerburg
  • 39
  • 1
  • 8
  • Just a few things that might cause problems. Your XY coordinates, speed, and angle _should_ be treated as doubles. By using integers you'll introduce quite a bit of creep and roundoff error (especially when dealing with radians) You may also consider introducing explicit Degrees/Radians classes to avoid possible cases of mixing the two. Additionally, consider taking advantage of Polar Coordinates to denote velocity (angle + speed). Here are samples of both: http://stackoverflow.com/questions/12126907/when-should-i-define-a-explicit-or-implicit-conversion-operator-in-c/12232002#12232002 – Chris Sinclair Oct 01 '12 at 12:54

2 Answers2

1

Math.Atan2 returns a value in radians, so are other c# trigonometric functions.

double angle = Math.Atan2(yDirection, xDirection);

Also make sure to force type casts to decimals:

3.0 * Math.Cos(radians);
mrvux
  • 8,523
  • 1
  • 27
  • 61
1

I'm betting the main problem you're seeing is this line:

int angleInDegrees = (int)Math.Atan2(xDirection, yDirection);

As @catflier mentioned, Math.Atan2 returns the angle in radians (so a number ranging from 0 to 2pi). However, you perform a cast to int which will truncate the decimal places. So if your angle was at 45 degrees, that's actually returning ~0.785398 radians. A cast to int will turn it into 0. Similarly, at 90 degrees, that's ~1.570796 radians, a cast to int will result in 1. That's significant round-off error. As I mentioned in my comment, consider changing all your types to doubles and only perform integer casts at the last point possible (I suppose your objects are positioned based on integers).

Chris Sinclair
  • 22,858
  • 3
  • 52
  • 93