Raheel Khan
Raheel Khan

Reputation: 14777

Detecting light projections in 2D space using C#

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?

Upvotes: 0

Views: 209

Answers (1)

Zong
Zong

Reputation: 6230

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.

Upvotes: 2

Related Questions