Threejs-Dont hit the spikes

案例源码
01

功能介绍

按上下左右,可以移动位置,碰到尖刺,结束游戏!回到起点,重启游戏!

代码细节

引入资源

  • three.js - 核心
  • gasp.min.js - 动画库 - 移动用
  • jquery - 控制Js
1
2
3
https://unpkg.com/three@0.128.0/build/three.js
https://unpkg.co/gsap@3/dist/gsap.min.js
https://code.jquery.com/jquery-3.6.0.min.js

场景搭建

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
var scene = new THREE.Scene();
scene.background = new THREE.Color('#001d45');
scene.fog = new THREE.Fog('#001d45', 10, 300);

var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 10;
camera.position.y = 2;

var renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);


// BoxGeo - 地板 / 天花板
var floorgeo = new THREE.BoxGeometry(30, 0.5, 500);
var floormat = new THREE.MeshLambertMaterial({
color: 0x0000aa
});
var floormesh = new THREE.Mesh(floorgeo, floormat);
scene.add(floormesh);

var ceilinggeo = new THREE.BoxGeometry(30, 0.5, 500);
var ceilingmat = new THREE.MeshLambertMaterial({
color: 0x0000aa
});
var ceilingmesh = new THREE.Mesh(ceilinggeo, ceilingmat);
scene.add(ceilingmesh);
ceilingmesh.position.y = 15;

// 尖刺 - 障碍物
var cones = [];
for (var i = 0; i < 1000; i++) {
let h = 5; // 高度 5 / 10
if (Math.random() <= 0.33) h = 10;

var geometry = new THREE.ConeGeometry(3, h, 10);
var material = new THREE.MeshBasicMaterial({
color: '#fcba03'
});

var cone = new THREE.Mesh(geometry, material);
cones.push(cone);
scene.add(cone);
cone.position.z = -i * 30 - 30; // -30 0 30 60 每隔30出现一个!
cone.originalZ = -i * 30 - 30; // 记录原位置!
cone.h = h;
if (Math.random() <= 0.5) { // 翻转! 360
cone.position.y = 15;
cone.rotation.z = Math.PI;
}
// 左右偏移
let dirR = Math.random(); // -7.5 0 7.5
if (dirR <= .33) cone.position.x = -7.5;
if (dirR >= .66) cone.position.x = 7.5;
}

总结