Posted: Mon Aug 24, 2009 6:37 am Post subject: [Release] Getting vector components by angle and length
What I'm presenting here is a function which, as the title states, returns a vector with the properties specified. This is useful for when you want the player to be able to move in more than the four regular directions(N/S/W/E).
What you can use it for:
Say you have a game where you want to give an object complete freedom in which direction it should move. This function could then be used to determine the new position of the object when it moves, given the length it should move, and it's current direction.
N.B:
- The Y- axis is reversed.
- Angle is in degrees.
- Angle 0 goes along the X-axis.
Code:
public Point GetVectorByLengthAndAngle(double length, double angle)
{
if (length == 0)
return new Point(0, 0);
else if (length < 0)
throw new ArgumentException("Length cannot be negative.");
if (360< angle || angle < 0)
throw new ArgumentException("Angle cannot be negative or bigger than 360.");
double angleBuf = (((90 < angle && angle <=180)||(270 < angle && angle<=360)) ? 90 - (angle % 90) :(angle % 90))/(180/Math.PI) ;
return new Point((int)(length * Math.Cos(angleBuf) * ((90 < angle && angle <= 270) ? -1 : 1)),(int)(length * Math.Sin(angleBuf) * ((180 <= angle && angle <= 360) ? 1 : -1)));
}
As always, all feedback is appreciated. _________________
Never confuse activity with productivity. You can be busy without a purpose, but what's the point?- Rick Warren
Joined: 17 Feb 2008 Posts: 524 Location: Inside the Intel CET shadow stack
Posted: Mon Aug 24, 2009 7:20 am Post subject:
Good work. The math is solid
Instead of throwing an exception when length is negative, why not simply take its absolute value and flip the angle by 180 degrees? Also, it is reasonably simple to correct for negative angles and angles over 360.
Just a side note: a length and angle from a known line is called a polar coordinate. _________________
It's not fun unless every exploit mitigation is enabled.
Please do not reply to my posts with LLM-generated slop; I consider it to be an insult to my time.
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum You cannot attach files in this forum You can download files in this forum