Raycast

Aim through two walls. Which wall stops the solid line, and where does the dotted line continue?
Interactive demo#CollisionDarkwood
Shooting an invisible line and asking what it hits first.
Used for instant bullets, for checking whether an enemy can see you, and for finding the ground under a character’s feet. The solid line stops at the first wall; the dotted line is where it would have gone.
Code
namespace raycast_lesson;
import stage;
import std;
import math;
var probe = CourierTurn {};
export "raycast" fn draw(time: f64, dt: f64, px: f64, py: f64, hover: bool) {
tiles();
let walls = [[70, 8, 10, 36], [112, 38, 12, 44], [58, 72, 30, 8], [140, 6, 8, 30]];
let length = hypot(px - 22, py - 50);
let aim = if length > 0 { atan2(py - 50, px - 22) } else { probe.facing };
let face = steer_courier(probe, time, 22, 50, 0, 0, aim);
let ux = if length > 0 { cos(face) } else { 0.0 };
let uy = if length > 0 { sin(face) } else { 0.0 };
var x = 22.0;
var y = 50.0;
for sample in 480 {
x = 22 + ux * sample * 0.5;
y = 50 + uy * sample * 0.5;
var hit = x < 0 || y < 0 || x > W || y > H;
for w in walls {
if x >= w[0] && x < w[0] + w[2] && y >= w[1] && y < w[1] + w[3] {
hit = true;
break;
}
}
if hit {
break;
}
}
for w in walls {
cabinet(w[0], w[1], w[2], w[3]);
box(w[0], w[1], w[2], w[3], INK);
}
line(x, y, 22 + ux * 240, 50 + uy * 240, LINE, 2, 3);
line(22, 50, x, y, WHITE);
rect(x - 2, y - 2, 5, 5, MAG);
draw_steering_courier(probe);
}

Comments
No comments yet.