问题
A light source is an entity in 2D space that sits in a single coordinate.
There are multiple light sources around in various locations and each gives off 8 rays of light in directions N, S, E, W, NW, NE, SW, SE
. The coordinates of all lights are known.
Given a random point (x, y)
, I need to determine if it is being hit by a ray of light.
int width = 10000;
int height = 10000;
List<Point> lights = a bunch of randomly placed light sources.
Point position = new Point(8888, 5555);
Now I need to iterate the lights' collection and determine if my location (
position`) is being hit by each.
A simple check for lights[n].X == position.X
could tell me a horizontal hit and similarly vertical. How do I detect the diagonal hits in the most efficient way possible? Since the diagonal is always at 45 degree angles, can I avoid costly floating point calculations?
回答1:
Why not just use:
Math.abs(lights[n].X - position.X) == Math.abs(lights[n].Y - position.Y)
Using angles (trig functions) will almost definitely be slower and more complex.
来源:https://stackoverflow.com/questions/11679828/detecting-light-projections-in-2d-space-using-c-sharp