Ray casting in 2D game engines
source link: https://sszczep.github.io/ray-casting-in-2d-game-engines/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Introduction
In my opinion, ray casting is a beautiful concept that is not that hard to grasp, but the quality resources are rare. We will learn the math behind it so you can implement it in your future projects with ease. I will try to make it as comprehensible as possible, explain all the caveats and issues you may stumble upon. We will also talk about optimization and how can spatial hash maps significantly help you. I will also provide some basic live examples for you to try out. Please note that demos were written to be as simple as possible, do not expect enterprise-grade code - we only learn about the concept, not the implementation.
What is ray casting?
Wikipedia on Ray castingRay casting is the most basic of many computer graphics rendering algorithms that use the geometric algorithm of ray tracing. Ray tracing-based rendering algorithms operate in image order to render three-dimensional scenes to two-dimensional images... The idea behind ray casting is to trace rays from the eye, one per pixel, and find the closest object blocking the path of that ray – think of an image as a screen-door, with each square in the screen being a pixel. This is then the object the eye sees through that pixel.
Well, it does not tell us much, does it? Let me simplify that. Ray casting is a fundamental and popular technique used to determine the visibility of specific objects (polygons) by tracing rays from the eye (for instance, player’s hero) on every pixel (well, not quite in our case - more on that later) and finding the nearest intersections with objects.
Where might ray casting be used?
Ray casting has many uses, especially in three-dimensional space. I outlined three, in my opinion, the most important, which are commonly used in 2D game engines:
Creating 3D perspective in a 2D map
The most well-known game that used this technique is Wolfenstein 3D. Rays were traced to determine the closest objects, and their distance from the player position was used to appropriately scale them.
Simple raycasting with fisheye correction by Lucas VieiraPoint-in-polygon problem
PIP problem asks whether a given point lies inside, outside, or on the boundary of a polygon. Using the ray casting algorithm, we can count how many times the point intersects the edges of the polygon. If the number of the intersections is even, the point is on the outside of the polygon. If the number of the intersections is odd, the point is on the inside or on the boundary of a polygon.
Point-in-polygon problem using ray castingObject visibility and light casting
This is the problem we will specifically tackle in this article - determining which objects are visible by the player and illuminating the visible area.
Object visibility and light castingObject visibility and light casting in 2D games
In this section we will go through basics such as calculating intersection points, casting rays, sorting intersection points to illuminate the visible area, and few words about circles. I will provide interactive demos at each stage so you do not get lost and see the results immediately.
Line-segment - ray intersection point
It is all about those intersection points. Let's learn step by step how to find them and how to use them. We will derive a line parametric equation first, calculate intersection points and finally learn how to determine which one of them is the closest efficiently.
Deriving line parametric equation
Let us talk about lines and their parametric equation first.
Simple line exampleWe can express vector AP→ by the following equation: AP→=tAB→, where t is an equation parameter defining how much do we stretch (|t|>1) or shrink (|t|<1) and if we flip the direction (t<0) of vector AP→ in relation to vector AB→.
Let me show you few examples:
Line parametric equation parameter exampleAs you might have noticed, we can use t as a scale factor: |AP|=|t||AB|. We will use that fact when determining the closest intersection point.
Now we can easily see, that if we want the point to be contained on:
- line: t∈R,
- ray: t≥0,
- line-segment: 0≤t≤1.
Having all of that sorted out, we can finally derive the parametric equation:
AP→=tAB→P−A=t(B−A)P=t(B−A)+A
If you still do not know what happens here, I can recommend an awesome short lecture by Norm Prokup: Parametrizing a Line Segment - Concept.
Calculating the intersection point
Assume that point P is the intersection point of line-segment defined by points A and B, and ray defined by points C and D. Point P is then expressed by set of two equations: {P=s(B−A)+A, where 0≤s≤1, andP=r(D−C)+C, where r≥0.
Solve for s and r: {s(Bx−Ax)+Ax=r(Dx−Cx)+Cx⇒s=r(Dx−Cx)+(Cx−Ax)Bx−Axs(By−Ay)+Ay=r(Dy−Cy)+Cy⇒r=s(By−Ay)+(Ay−Cy)Dy−Cy
Substitute s into the second equation: r(Dx−Cx)+(Cx−Ax)Bx−Ax(By−Ay)+Ay=r(Dy−Cy)+Cyr(Dx−Cx)(By−Ay)Bx−Ax+(Cx−Ax)(By−Ay)Bx−Ax+Ay=r(Dy−Cy)+Cyr((Dx−Cx)(By−Ay)Bx−Ax−(Dy−Cy))=(Cy−Ay)−(Cx−Ax)(By−Ay)Bx−Axr(Dx−Cx)(By−Ay)−(Dy−Cy)(Bx−Ax)Bx−Ax=(Cy−Ay)(Bx−Ax)−(Cx−Ax)(By−Ay)Bx−Axr=(Cy−Ay)(Bx−Ax)−(Cx−Ax)(By−Ay)(Dx−Cx)(By−Ay)−(Dy−Cy)(Bx−Ax)r=(Bx−Ax)(Cy−Ay)−(Cx−Ax)(By−Ay)(Dx−Cx)(By−Ay)−(Bx−Ax)(Dy−Cy)
Substitute r into the first equation: s(Bx−Ax)+Ax=s(By−Ay)+(Ay−Cy)Dy−Cy(Dx−Cx)+Cxs(Bx−Ax)+Ax=s(By−Ay)(Dx−Cx)Dy−Cy+(Ay−Cy)(Dx−Cx)Dy−Cy+Cxs((By−Ay)(Dx−Cx)Dy−Cy−(Bx−Ax))=(Ax−Cx)−(Ay−Cy)(Dx−Cx)Dy−Cys(By−Ay)(Dx−Cx)−(Bx−Ax)(Dy−Cy)Dy−Cy=(Ax−Cx)(Dy−Cy)−(Ay−Cy)(Dx−Cx)Dy−Cys=(Ax−Cx)(Dy−Cy)−(Ay−Cy)(Dx−Cx)(By−Ay)(Dx−Cx)−(Bx−Ax)(Dy−Cy)s=(Ax−Cx)(Dy−Cy)−(Dx−Cx)(Ay−Cy)(Dx−Cx)(By−Ay)−(Bx−Ax)(Dy−Cy)
Having s and r calculated, we can calculate P using one of the equations from the set.
Demo 1 - all intersection pointsFinding the closest intersection point
We only need the closest intersection point to properly draw the visible area. The naive solution would be to calculate distances between the ray starting point and intersection points using the Pythagorean Theorem: (Cx−Px)2+(Cy−Py)2. Remember the line equation parameter, though? I have already mentioned that we can use it as a scale factor. As we want to compare distances on ray, we can check for the smallest r parameter value: |CP1→|<|CP2→|⇔|r1|<|r2|.
Demo 2 - the closest intersection pointCasting rays
In the following section we will go through two different ways rays might be cast. We will compare them and mention their pros and cons.
Casting rays by offset angle
First way is to cast rays in all directions by specified offset angle. For instance, we could cast 30 rays in total offseted by 12∘. Let's see how to generate all those rays first.
Let P1=(x1,y1) be an anchor point of our rays, and let P2=(x2,y2) be a some point on a line going through P1 at angle ϕ:
Line from given point at some angle
We can define x2 as x1+dx and y2 as y1−dy (our y-axis is inverted hence why the minus sign).
Now we need to derive formulas for dx and dy:
{sin(ϕ)=dydist⇒dy=dist∗sin(ϕ)cos(ϕ)=dxdist⇒dx=dist∗cos(ϕ)dist in our case has an arbitrary (greater than 0) value (we are looking for any point on the line), so we are safe to assume dist=1 to simplify the calculations. Having it all considered, P2=(x1+sin(ϕ),y1−cos(ϕ)), where ϕ is our angle offset.
Casting rays on vertices
Casting rays on vertices is most likely your go-to solution. Instead of casting rays in all directions, we can simply cast them on our polygons' vertices. Depending on the number of vertices, we can save computing power by not casting useless rays. In the next sections you will see how does it impact animation smoothness and also learn how to further optimize the whole process.
Demo 4 - casting rays on verticesIlluminating the visible area
This is where the real fun begins. We will illuminate the visible area by filling a giant polygon.
Sorting intersection points
To correctly order vertices to build a proper polygon, we need to sort them by angle first. We will use atan2(y,x) function for that. You can read more about it here.
Let's compare both ray casting methods:
Both of them looks glitchy, jumpy and inaccurate. Let's take a closer look why.
Casting slightly offseted rays
Notice what happens when rays are cast directly on vertices - they should go beyond that vertex but we are getting only the closest intersection point:
Rays on vertices problem
The most common solution is casting two extra rays offseted by small angle (in both directions) for every cast ray. Consider ray AB starting at A=(Ax,Ay) going through B=(Bx,By). We want to find such point C=(Cx,Cy) that ray AC would be rotated by ϕ with A being the origin point. C coordinates would be as follow:
{Cx=(Bx−Ax)cos(ϕ)−(By−Ay)sin(ϕ)+AxCy=(By−Ay)cos(ϕ)+(Bx−Ax)sin(ϕ)+Ay
Note that we do not need to do it for the first method - simply add or substract the offset from the angle we are calculating from.
For further explanation you can check this article.
Let's see how the illumination behaves after changes:
It did not help much for the first method. We could decrease angle offset (hence increase number of rays) but the result will still be poor. On the other hand, the second method looks very smooth and accurate. From now on, we will not be talking about the first method anymore.
Visibility circle and flashlight
We may want to somehow limit player's visibility. We can achieve that by creating a clipping region of desired shape. In the demos below, I used a CanvasRenderingContext2D.clip() method.
As you might have noticed, there is no optimization whatsoever - we are still calculating all the intersection points. We will get back to it once we learn about spatial hashmaps.
What about circles?
I have rarely seen a real use-case scenario for ray casting on circles. Please treat this section as an extra where I only briefly talk about it. I will provide you with equations and basic demos, the rest is up to you.
Circle - ray intersection point
Let P be an intersection point, A a ray's anchor point, B a point on the ray, C a circle's center point and r a circle's radius. {Px=t(Bx−Ax)+AxPy=t(By−Ay)+Ayr2=(Px−Cx)2+(Py−Cy)2
Solve for t:
r2=Px2−2PxCx+Cx2+Py2−2PyCy+Cy2r2=(t(Bx−Ax)+Ax)2−2(t(Bx−Ax)+Ax)Cx+Cx2+(t(By−Ay)+Ay)2−2(t(By−Ay)+Ay)Cy+Cy2r2=t2(Bx−Ax)2+2t(Bx−Ax)Ax+Ax2−2t(Bx−Ax)Cx−2AxCx+Cx2+t2(By−Ay)2+2t(By−Ay)Ay+Ay2−2t(By−Ay)Cy−2AyCy+Cy20=t2((Bx−Ax)2+(By−Ay)2)+2t((Bx−Ax)Ax−(Bx−Ax)Cx+(By−Ay)Ay−(By−Ay)Cy)+Ax2−2AxCx+Cx2+Ay2−2AyCy+Cy2−r20=t2((Bx−Ax)2+(By−Ay)2)+2t((Bx−Ax)(Ax−Cx)+(By−Ay)(Ay−Cy))+(Ax−Cx)2+(Ay−Cy)2−r2
Solve the quadratic equation:
{a=(Bx−Ax)2+(By−Ay)2b=2((Bx−Ax)(Ax−Cx)+(By−Ay)(Ay−Cy))c=(Ax−Cx)2+(Ay−Cy)2−r2Δ=b2−4ac
- Δ<0: ray does not intersect the circle,
- Δ=0: ray intersects the circle in one point (tangent),
- Δ>0: ray intersects the circle in two points.
Only if Δ=0:
t=−b2a
Only if t≥0:
{Px=t(Bx−Ax)+AxPy=t(By−Ay)+Ay
Only if Δ>0:
{t1=−b−Δ2at2=−b+Δ2a
Only if ti≥0:
{Pix=ti(Bx−Ax)+AxPiy=ti(By−Ay)+Ay
Demo 11 - circle - ray instersection
Casting rays on circles
We need to find two tangent lines to a given circle passing through a ray anchor point.
Let Pi be tangent points, A a ray's anchor point, C a circle's center point and r a circle's radius.
We will also be moving all points using translation vector v→=(−Cx,−Cy): X′=X+v→, so the circle's center is at (0,0).
From the circle equation:
Px′2+Py′2=r2
From the perpendicular line to the circle's radius:
Py′Px′=−1Py′−Ay′Px′−Ax′Py′Px′=−Px′−Ax′Py′−Ay′−Py′2+Py′Ay′=Px′2−Px′Ax′Px′2+Py′2=Px′Ax′+Py′Ay′ Solve the equation system:
{Px′2+Py′2=r2Px′2+Py′2=Px′Ax′+Py′Ay′r2=Px′Ax′+Py′Ay′Px′=r2−Py′Ay′Ax′, where Ax′≠0
Substitute Px′ into the first equation:
(r2−Py′Ay′Ax′)2+Py′2=r2r4−2r2Py′Ay′+(Py′Ay′)2Ax′2+Py′2=r2r4−2r2Py′Ay′+(Py′Ay′)2+Py′2Ax′2=r2Ax′2Py′2(Ax′2+Ay′2)−Py′2r2Ay′+r4−r2Ax′2=0
Solve the quadratic equation:
{a=Ax′2+Ay′2b=−2r2Ay′c=r4−r2Ax′2Δ=b2−4ac
- Δ<0: there are no tangent points (ray's anchor point is in the circle),
- Δ=0: there is only one tangent point (ray's anchor point),
- Δ>0: there are two tangent points.
Only if Δ=0:
{Py′=−b2aPx′=r2−Py′Ay′Ax′{Px=Px′+CxPy=Py′+Cy
Only if Δ>0:
{P1y′=−b−Δ2aP2y′=−b+Δ2aPix′=r2−Piy′Ay′Ax′{Pix=Pix′+CxPiy=Piy′+Cy
There is still one issue - it will not work if Ax′=0.
Take a closer look at the following equation: r2=Px′Ax′+Py′Ay′.
If Ax′=0, the equation becomes: r2=Py′Ay′ - we cannot substitute Px′ anymore.
Here are the steps for solving the equation system once that happens:
Solve the equation system:
{Px′2+Py′2=r2Px′2+Py′2=Px′Ax′+Py′Ay′Ax′=0r2=Py′Ay′Py′=r2Ay′, where Ay′≠0
Substitute Py′ into the first equation:
Px′2+(r2Ay′)2=r2Px′2+r4Ay′2=r2Px′2Ay′2+r4=r2Ay′2Px′2Ay′2+r4−r2Ay′2=0
Solve the quadratic equation:
{a=Ay′2b=0c=r4−r2Ay′2Δ=b2−4ac
- Δ<0: there are no tangent points (ray's anchor point is in the circle),
- Δ=0: there is only one tangent point (ray's anchor point),
- Δ>0: there are two tangent points.
Only if Δ=0:
{Px′=−b2aPy′=r2Ay′{Px=Px′+CxPy=Py′+Cy
Only if Δ>0:
{P1x′=−b−Δ2aP2x′=−b+Δ2aPiy′=r2Ay′{Pix=Pix′+CxPiy=Piy′+Cy
Note that we can do the same for Ay′=0, however, it is optional.
If Ax′=Ay′=0, there are no solutions.
Few optimization techniques
In this section, we will discuss the usage of spatial hashmaps and modified Bresenham's line algorithm. I will not go into implementation details as they are commonly available on the Internet. I will, however, provide you with some demos to try these out and come up with your own ideas on where to use them.
Spatial hashmaps
Currently, we are drawing all polygons and calculating all intersection points, but it is pretty much useless. In most cases, our play area will be much bigger than the viewport. By using spatial hashmaps, we can quickly determine which polygons are visible to the player and perform adequate calculations.
Basically, we want to divide the play area into smaller cells (of predefined size). Each cell consists of a list containing our shapes (most likely line-segments). If a single shape spans across multiple cells, it will be included in all of them.
The name of this technique suggests using hashmaps (eg. cells would be named something like X+":"+Y), but in our case, using a simple 2D array might be more desired.
Here is a simple demo showing how it might work:
We can use them for viewports as mentioned previously, and also visibility circles and flashlights.
Bresenham-based supercover line algorithm
Well, it is high time we did something with finding the closest intersection points. Using spatial hashmaps and modified Bresenham's line algorithm, we can traverse the grid in an efficient manner making as few checks as required. The algorithm should stop when the first cell with an intersection point is found.
You can read more about Bresenham's line algorithm here, and its modified version here.
Everything has an end
Sorry, unfortunately, I mean this article and not rays.
I think I have covered everything to help you get started. I will try my best to expand it in the future if I spot something needing an additional explanation. I have also created a little cheatsheet for you to quickly recap some of the topics and derived formulas.
If you enjoyed the read be sure to star and watch this repository on GitHub. You might also want to follow me for more content like that in the future. Also do not forget to create an issue if one of the topics seems to be poorly explained or you have other suggestions.
Stay tuned for more!
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK