Search code examples
c#geometrydrawing2d

Lines and shapes drawn at incorrect angles


I have a c# program where I need to draw some simple 2D objects on the canvas.

One of these involves drawing a rectangle and lines where I know the start point, the length and I have to calculate the end position. So I have the following code;

 private void CalculateEndPoint()
 {
            double angle = Helper.deg2rad((double)this.StartAngle);
            int x = this.StartPoint.X + (int)(Math.Cos(angle) * this.Length * -1);

            int y = this.StartPoint.Y + (int)(Math.Sin(angle) * this.Length);
            this.EndPoint = new Point(x, y);
 }

Now this seems to work OK to calculate the end points. The issue I have is with the angle (this.StartAngle), the value I specify seems not to be how it is drawn and I seem to have the following;

Circle degrees

Where as I'm expecting 0 at the top, 90 on the right, 180 at the bottom etc.

So to get a shape to draw straight down the canvas I have to specify 90 degrees, where as I would expect to specify 180.

Have I done something wrong? Or is it just a lack of understanding?


Solution

  • You should change your CalculateEndPoint function to have that:

    private static void CalculateEndPoint(double dec)
    {
        double angle = (Math.PI / 180) * (this.StartAngle + 90); // add PI / 2
        int x = StartPoint.X + (int)(Math.Cos(angle) * Length * -1);
    
        double angle2 = (Math.PI / 180) * (this.StartAngle - 90); // minus PI / 2
        int y = StartPoint.Y + (int)(Math.Sin(angle2) * Length);
        EndPoint = new Point(x, y);
    }