Question

Lets say I'm moving my mouse in a circle with the end point of a line following the mouse position. When holding down Left-Ctrl the end point of this line should stick to a 45 degrees depending on the angle the end-point has to the start-point of the line.

Note that I am viewing the line from ABOVE (y+) looking straight down at origo, that's why I'm using X and Z to define the position.

This is how far I've gotten. So I got the closest 45 degree angle, now I only need to calculate the correct end-point for the line.

p1 = Start point of line

p2 = End point of line (mouse position)

if (l_vIsCtrlPressed) {
   var length = Algo.Length(p1, p2);
   var angle = Algo.Angle(p1, p2);
   angle = Algo.ConvertToDegree(angle);
   angle = Math.round(angle / 45) * 45;
}

I tried using the following calculation but with no success.

p2.x = p1.x - length * Math.cos(angle);
p2.z = p1.z - length * Math.sin(angle);

Angles(degree)

0 LEFT

-90 DOWN

90 UP

180 && -180 RIGHT

Was it helpful?

Solution

I forgot to convert the angle back to radians -.-" The following code fixes my issue. Line is now drawn with an angle with degree 0, 45, 90, 135, 180.. etc

if (l_vIsCtrlPressed) {
    var length = Algo.Length(p1, p2);
    var angle = Algo.Angle(p1, p2);
    angle = Algo.ConvertToDegrees(angle);
    angle = Math.round(angle / 45) * 45;
    angle = Algo.ConvertToRadians(angle); // FORGOT TO CONVERT BACK TO RADIANS

    p2.x = p1.x - length * Math.cos(angle);
    p2.z = p1.z - length * Math.sin(angle);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top