-
Notifications
You must be signed in to change notification settings - Fork 0
/
raycast.html
87 lines (77 loc) · 2.54 KB
/
raycast.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Raycasting Collision Detection in WebGL</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
}
canvas {
display: block;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/three.min.js"></script>
<script>
// Set up the scene, camera, and renderer
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
1000
);
// Move the camera away from the objects
camera.position.set(0, 10, 20);
camera.lookAt(scene.position);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Add a cube to act as an obstacle
const obstacleGeometry = new THREE.BoxGeometry(5, 5, 5);
const obstacleMaterial = new THREE.MeshBasicMaterial({ color: 0x0000ff });
const obstacle = new THREE.Mesh(obstacleGeometry, obstacleMaterial);
obstacle.position.set(0, 0, -10);
scene.add(obstacle);
// Add a cube to act as the player
const playerGeometry = new THREE.BoxGeometry(1, 1, 1);
const playerMaterial = new THREE.MeshBasicMaterial({ color: 0xff0000 });
const player = new THREE.Mesh(playerGeometry, playerMaterial);
player.position.set(5, 0, 0);
scene.add(player);
// Set up the raycaster
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();
// Move the player based on keyboard input
const keyboard = {};
document.addEventListener("keydown", (event) => {
keyboard[event.key] = true;
});
document.addEventListener("keyup", (event) => {
keyboard[event.key] = false;
});
function animate() {
// Move the player based on keyboard input
if (keyboard["a"]) player.position.x -= 0.1;
if (keyboard["d"]) player.position.x += 0.1;
if (keyboard["w"]) player.position.z -= 0.1;
if (keyboard["s"]) player.position.z += 0.1;
// Cast a ray from the player to check for collisions with the obstacle
raycaster.set(player.position, new THREE.Vector3(0, 0, -1));
const intersections = raycaster.intersectObject(obstacle);
if (intersections.length > 0) {
alert("Boom!");
}
// Render the scene
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
animate();
</script>
</body>
</html>