Ray Tracing (?)

2 posts

Flag Post

Problem: Given a point and an angle, draw a imaginary line and place many points equidistantly from each other on the line (i.e. 30 pixels apart).

So, I’m working on my entry for GiTD 28 and I’ve hit a small roadblock. In all previous games I’ve just spawned a bullet, set its velocity, and hit-tested it until it was removed. In this game I want to be able to get the angle of a turret, and draw an (imaginary) line, place a ton of points along the line, and then test those. I think this is called ray tracing, correct?

Anyways, here’s what I want to do in picture form:

I’m in Geometry right now so ELI9thGrader would be nice. I’m just not too sure about the math, I’m assuming I’ll have to do some vector math right?


Flag Post

Ray tracing usually refers to the tracing of light rays for rendering, in my experience.

But yes, what you need is some simple geometry.

First find the direction vector from the turret to the mouse location. That’s simply (mouse location-turret location) scaled down to a size of 1. I.e. if the turret is at [50, 0] and the mouse is at [250, 120], the difference is [200, 120] and the direction vector is
d = (1/√(200²+120²))×[200, 120] = [0.857, 0.514].

Then to find the point a distance s along that line from the turret, simply add _s_×*d* to the turret location ([50, 0] in our example).

E.g. the first two shots, at 30 and 60 pixels along it, are at
[50, 0] + 30×[0.857, 0.514] = [75.72, 15.43]
[50, 0] + 60×[0.857, 0.514] = [101.4, 30.87]

To draw your line just pick the range you want it drawn (you can use 1000px or something if you always want it to go across the whole screen) and use the same approach to find the endpoint.

Edit: I didn’t actually use an angle here, because it looks like you are trying to aim towards a target. If you have an angle already, then the direction vector is
[cos a, sin a]
… or something similar, depending on where 0 angle is and which direction the rotation is measured in.