How to code a ray cast

Christoph Krassnigg
3 min readJan 7, 2021

Most of you out there know the classic 3D games which were basically 2D. I am talking about the first Doom and Wolfenstein.
This article will cover how you can code the 2D part, which is actually very simple with a math function.

If you are only interested in the code, then go and check it out here.

Setting up

For our basic example, we are using Processing. We can use Processing for coding Java in a more simplified way. It provides us with every Java feature, but it also makes it easier to get started as a newbie.

Download Processing here.

Playground

We need a playground to test if our raycasting is actually working. You can add more walls as you want.

We are creating a list of walls, with which our rays are colliding with.

Here is the look of the playground. It is straightforward and useful for testing.

Ray casting

Now add some rays. Anytime, there should be 360 rays around the mouse which should be cast against walls. Let us add them…

The maths behind it is simple. We need a formula from Wikipedia which looks complex, but we are just putting in our values. We have two lines, our ray and the wall. We calculate if and where those intersect.

If we have an intersection point, we can calculate the distance between the start point and the intersection point, in the code, it is called an “end” point.

We do this with every wall, and we take the intersection point, which gives us the smallest possible length. We calculate our line length with the Pythagorean theorem by putting in the start and intersection point.

Otherwise, our ray would go straight throw walls. If you want to do something crazy, then change it in a way, where it takes the second smallest value, and your ray will cast through one wall, but it will be blocked by the next one. Imagine Doom would have been written in this way, what a nightmare!

Now let us add a “Ray” object which uses our previous written wall class.

To not forget to update your draw() function, otherwise, we do not calculate any raycasting. I added a for loop, which generates 360 different rays, each ranging from 0–359°.

Now, look at the result!

This looks beautiful, and it is fun to play around with. If you need some extra challenge, add a wall builder as in the GitHub repository. Pressing with your left mouse button selects the starting point, then pressing again selects an endpoint and you added a wall! A simple way for building maps.

Check out my GitHub repository if you want to see my implementation, otherwhise feel free to ask me in the comment section if something is unclear.

--

--

Christoph Krassnigg
Christoph Krassnigg

Written by Christoph Krassnigg

Developer at block42. Student. Java fanatic. Loves to write about techy things.

Responses (5)