-
Notifications
You must be signed in to change notification settings - Fork 15
RayCasting
This is the most important page of the tutorial. To start our logic, we need to know some concepts with the player angle, player FOV and Screen width.
The first thing we have to know is that each ray needs to be throwed in relation of the player angle and the field of view (FOV). The player FOV is 60º, but the player focus is in the middle of the FOV. Because this we have to start the RayCasting in -30º of the player angle. For example, if the player angle is 90º, we have to cast the rays from the 60º angle to 120º angle. Check the image below to see the player FOV representation.
Inside our rayCasting() function, we can get the actual ray angle with this code
function rayCasting() {
let rayAngle = data.player.angle - data.player.halfFov;
}After it, we will start the cast of the rays. Remember that we have to iterate all screen slices, so we will use the screen width to do this. For each iteration the rayAngle variable needs to be incremented to iterate the entire player FOV. We will use the data.rayCasting.incrementAngle to do it.
function rayCasting() {
let rayAngle = data.player.angle - data.player.halfFov;
for(let rayCount = 0; rayCount < data.screen.width; rayCount++) {
// ...
// Increment
rayAngle += data.rayCasting.incrementAngle;
}
}The next steps will be created inside the ray loop, and before the ray angle increment. Tthe first coordinates of the ray is the the same of the player coodinates. We will create an object with these values to be more organized.
// Ray data
let ray = {
x: data.player.x,
y: data.player.y
}To discover the next coordinates of the actual ray, we have to calculate this based in the ray angle. For this step, we will use the functions Math.sin and Math.cos. These functions will give to usthe increment values to give for the ray to follow forward. In this step we will use the precision attribute too, to control the interval of each position of the ray. The sin and cos give us float values, but we can divide these values with the precision to turn these values
smaller.
Note: The higher value of the precision, more checkings will be executed and more positions the ray will have.
Note: We need to use the
degreeToRadians()function in this step because the trigonometry functions work with radians values type.
// Ray path incrementers
let rayCos = Math.cos(degreeToRadians(rayAngle)) / data.rayCasting.precision;
let raySin = Math.sin(degreeToRadians(rayAngle)) / data.rayCasting.precision;Copyright © 2018 Vinícius Reif Biavatti
- Home
- RayTrancing
- Examples
- Basic Tutorial
- Intermediary Tutorial
- Advanced Tutorial