The concept
Raycasting projects a ray from the camera into the scene to detect intersected objects. It's the basic selection mechanism in 3D and AR interfaces. In 2D, we simulate it by testing if the cursor (or finger) intersects geometric shapes.
The code
// Raycast: hit test on circles
let objects = [];
function setup() {
createCanvas(400, 280);
for (let i = 0; i < 8; i++)
objects.push({x:random(50,350), y:random(50,230), r:random(20,40), hit:false});
}
function draw() {
background(11, 15, 20);
for (let o of objects) {
o.hit = dist(mouseX, mouseY, o.x, o.y) < o.r;
noStroke();
fill(o.hit ? [55,227,195] : [60,70,90]);
ellipse(o.x, o.y, o.r*2);
}
// Ray line
stroke(200,200,200,60); strokeWeight(1);
line(mouseX, mouseY, mouseX, 0);
}Going further
Explore other free courses on the Workshops page.
Practice, collaborate, deploy — in 15 min.
Book a discovery call →