打造沉浸式 2D 赛道 3D 赛车游戏 ——Three.js 实战教程
前言
一款3d赛车游戏
本文将从核心概念到代码实现,一步步拆解这款 3D 赛车游戏的开发过程。文章中展示的代码均为可运行版本(基于 Three.js ),你可以直接复制到本地运行,也可以基于此进行二次开发。
初识 Three.js 核心三要素
想要开发 Three.js 3D 应用,必须先掌握场景 (Scene)、相机 (Camera)、渲染器 (Renderer) 这三大核心组件 —— 这是所有 Three.js 应用的基础骨架。
核心概念解析
场景 (Scene):
3D 世界的容器,所有的模型、灯光、雾效等都需要添加到场景中
相机 (Camera):
用户观察 3D 世界的视角,本文使用透视相机(PerspectiveCamera)模拟人眼的视觉效果
渲染器 (Renderer):
将相机视角下的场景渲染到 Canvas 画布上,负责 WebGL 上下文的管理
基础实现代码
class Game {
constructor() {
// 1. 创建场景 - 添加雾效增强沉浸感
this.s = new THREE.Scene();
this.s.fog = new THREE.Fog(0x87CEEB, 100, 400);
// 2. 创建透视相机 - 75°视场角,适配窗口比例,近裁切面0.1,远裁切面2000
this.cam = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 2000);
this.cam.position.set(0, 15, 25); // 初始第三人称视角位置
// 3. 创建WebGL渲染器 - 开启抗锯齿和阴影
this.r = new THREE.WebGLRenderer({ antialias: true, alpha: true });
this.r.setSize(window.innerWidth, window.innerHeight);
this.r.setClearColor(0x87CEEB); // 天空蓝背景
this.r.shadowMap.enabled = true; // 启用阴影
this.r.shadowMap.type = THREE.PCFSoftShadowMap; // 软阴影提升视觉效果
document.getElementById('game-container').appendChild(this.r.domElement);
// 初始化其他资源...
}
}
关键优化点
雾效 (Fog)
:添加线性雾效让远处的物体逐渐融入背景,避免画面边缘的突兀感
软阴影 (PCFSoftShadowMap):
相比硬阴影,软阴影更贴近现实,但性能消耗略高,适合轻量级游戏
抗锯齿 (antialias)
开启抗锯齿让渲染的边缘更平滑,提升视觉体验 游戏核心架构设计
本文采用面向对象的设计思路,将整个游戏封装在Game类中,遵循单一职责原则:
成员变量:管理场景、相机、渲染器、赛车、状态等核心资源
成员方法:按功能划分为初始化、更新、控制、渲染等模块
核心成员变量设计
class Game {
constructor() {
// 核心三要素
this.s = null; // 场景
this.cam = null; // 相机
this.r = null; // 渲染器
// 游戏状态 - 集中管理所有可配置参数和运行时状态
this.gs = {
// 按键状态
acc: false, // 加速(W)
dec: false, // 减速/倒车(S)
tl: false, // 左转(D)
tr: false, // 右转(A)
// 视角控制
lu: false, ld: false, ll: false, lr: false,
// 漂移状态
dr: false,
// 物理参数
sp: 0, // 当前速度(基准值)
msp: 8, // 最大前进速度
mrp: 4, // 最大倒车速度
ac: 0.15, // 加速度
fr: 0.08, // 正常摩擦力
dfr: 0.04, // 漂移摩擦力(更小,漂移时速度衰减慢)
// 转向参数
cta: 0, // 当前转向角度(显示用)
mta: 60, // 最大转向角度(°)
// 时间相关
lt: 0, // 上一帧时间
};
// 赛车相关
this.c = {
m: null, // 赛车模型(Group)
p: new THREE.Vector3(0, 1, 0), // 赛车位置
r: 0, // 赛车旋转角度
fw: [], // 前轮模型列表
rw: [] // 后轮模型列表
};
// 终点相关
this.t = {
m: null, // 终点锥形体模型
p: new THREE.Vector3(0, 0, -180) // 终点位置
};
// 初始化方法调用
this.initS(); // 初始化场景(光照、地面)
this.initC(); // 初始化赛车
this.initT(); // 初始化赛道
this.initTar(); // 初始化终点标识
this.initCtrl(); // 初始化控制器
// 启动游戏循环
this.lt = performance.now();
this.an();
}
}
设计思路
集中式状态管理 (gs)
:将所有可配置参数和运行时状态集中管理,便于后续调整和扩展(比如做难度调节功能)
结构化对象 (c/t)
:将赛车和终点的模型、位置等信息封装为对象,提高代码可读性
参数可配置化
:所有物理参数(如加速度、最大速度、摩擦力)都作为变量定义,无需修改核心逻辑即可调整游戏手感
游戏资源初始化
1. 场景初始化(光照 + 地面)
一个真实的 3D 场景需要光照来体现物体的立体感,本文使用环境光 + 平行光的组合:
initS() {
// 环境光 - 基础照明,避免阴影过暗
const al = new THREE.AmbientLight(0xffffff, 0.7);
this.s.add(al);
// 平行光 - 模拟太阳光,产生阴影
const dl = new THREE.DirectionalLight(0xffffff, 0.9);
dl.position.set(50, 80, 40); // 光源位置
dl.castShadow = true; // 开启阴影投射
// 阴影相机参数 - 控制阴影渲染范围
dl.shadow.camera.left = -250;
dl.shadow.camera.right = 250;
dl.shadow.camera.top = 250;
dl.shadow.camera.bottom = -250;
dl.shadow.mapSize.width = 2048; // 阴影分辨率(越大越清晰,性能消耗越高)
dl.shadow.mapSize.height = 2048;
this.s.add(dl);
// 地面 - 绿色草地
const gg = new THREE.PlaneGeometry(600, 600, 100, 100);
const gm = new THREE.MeshStandardMaterial({
color: 0x228B22,
roughness: 0.9, // 粗糙度(0=镜面,1=漫反射)
metalness: 0.1 // 金属度
});
const g = new THREE.Mesh(gg, gm);
g.rotation.x = -Math.PI / 2; // 平面默认是垂直的,旋转90°变为水平
g.receiveShadow = true; // 接收阴影
this.s.add(g);
}
2. 赛车模型构建
赛车模型采用基础几何体组合实现(无需外部 3D 模型),分为车身、驾驶舱、尾翼、车轮等部分:
initC() {
const cg = new THREE.Group(); // 赛车分组 - 便于整体控制
// 车身 - 红色长方体
const bg = new THREE.BoxGeometry(4, 1.2, 8);
const bm = new THREE.MeshStandardMaterial({ color: 0xFF0000 });
const b = new THREE.Mesh(bg, bm);
b.position.y = 0.6; // 离地高度
b.castShadow = true; // 投射阴影
cg.add(b);
// 驾驶舱 - 黑色长方体
const cpg = new THREE.BoxGeometry(2.5, 0.8, 3);
const cpm = new THREE.MeshStandardMaterial({ color: 0x000000 });
const cp = new THREE.Mesh(cpg, cpm);
cp.position.set(0, 1.2, -1);
cg.add(cp);
// 尾翼
const wg = new THREE.BoxGeometry(3, 0.2, 0.5);
const wm = new THREE.MeshStandardMaterial({ color: 0xFF0000 });
const w = new THREE.Mesh(wg, wm);
w.position.set(0, 1.5, 3.5);
cg.add(w);
// 车轮创建函数 - 复用代码
const cw = (x, z, f = true) => {
const wg = new THREE.Group();
// 轮胎 - 黑色圆柱体
const tg = new THREE.CylinderGeometry(0.8, 0.8, 0.5, 16);
const tm = new THREE.MeshStandardMaterial({ color: 0x111111 });
const t = new THREE.Mesh(tg, tm);
t.rotation.z = Math.PI / 2; // 旋转为水平
t.castShadow = true;
wg.add(t);
// 轮毂 - 灰色圆柱体
const rg = new THREE.CylinderGeometry(0.6, 0.6, 0.4, 16);
const rm = new THREE.MeshStandardMaterial({ color: 0xCCCCCC });
const r = new THREE.Mesh(rg, rm);
r.rotation.z = Math.PI / 2;
wg.add(r);
wg.position.set(x, 0.4, z); // 车轮位置
cg.add(wg);
return wg;
};
// 创建四个车轮
this.c.fw.push(cw(-2.2, 3, true)); // 左前轮
this.c.fw.push(cw(2.2, 3, true)); // 右前轮
this.c.rw.push(cw(-2.2, -3, false)); // 左后轮
this.c.rw.push(cw(2.2, -3, false)); // 右后轮
cg.position.copy(this.c.p);
this.c.m = cg;
this.s.add(this.c.m);
}
3. 赛道与终点初始化
赛道采用环形设计,终点线为金色,终点标识为发光的锥形体:
// 初始化赛道(环形)
initT() {
const tg = new THREE.Group();
const tw = 12; // 赛道宽度
const trs = 80; // 赛道半径
const tsg = 64; // 分段数(越大越平滑)
// 赛道基础 - 灰色环形
const tgeo = new THREE.RingGeometry(trs - tw/2, trs + tw/2, tsg);
const tmat = new THREE.MeshStandardMaterial({
color: 0x333333,
roughness: 0.8,
metalness: 0.1,
side: THREE.DoubleSide // 双面渲染
});
const tbase = new THREE.Mesh(tgeo, tmat);
tbase.rotation.x = -Math.PI / 2;
tbase.position.y = 0.05; // 略高于地面
tg.add(tbase);
// 赛道外边界线
const op = [];
for (let i = 0; i <= tsg; i++) {
const a = (i / tsg) * Math.PI * 2;
op.push(new THREE.Vector3(
Math.cos(a) * (trs + tw/2),
0.06,
Math.sin(a) * (trs + tw/2)
));
}
const olgeo = new THREE.BufferGeometry().setFromPoints(op);
const olmat = new THREE.LineBasicMaterial({ color: 0xFFFFFF, linewidth: 2 });
const ol = new THREE.Line(olgeo, olmat);
tg.add(ol);
// 赛道内边界线
// ...(类似外边界线,半径为trs - tw/2)
// 终点线 - 金色
const flp = [
new THREE.Vector3(-tw/2, 0.07, -trs),
new THREE.Vector3(tw/2, 0.07, -trs)
];
const flgeo = new THREE.BufferGeometry().setFromPoints(flp);
const flmat = new THREE.LineBasicMaterial({ color: 0xFFD700, linewidth: 4 });
const fl = new THREE.Line(flgeo, flmat);
tg.add(fl);
this.s.add(tg);
}
// 初始化终点标识(发光锥形体)
initTar() {
const tg = new THREE.ConeGeometry(3, 6, 8); // 圆锥几何体(半径3,高度6,8个分段)
const tm = new THREE.MeshStandardMaterial({
color: 0xFFD700,
emissive: 0xFFD700, // 自发光颜色
emissiveIntensity: 0.8 // 发光强度
});
const t = new THREE.Mesh(tg, tm);
t.position.copy(this.t.p);
t.position.y = 3; // 高度
t.castShadow = true;
this.t.m = t;
this.s.add(this.t.m);
}
输入控制系统
输入控制采用键盘事件监听,通过状态机记录按键的按下 / 抬起状态,避免连续触发问题:
initCtrl() {
const _this = this; // 保存this上下文
// 按键按下事件
const kd = function (e) {
if (_this.gs.over && e.code !== 'KeyR') return; // 游戏结束后仅响应R键重置
switch (e.code) {
case 'KeyW': _this.gs.acc = true; break; // 加速
case 'KeyS': _this.gs.dec = true; break; // 减速/倒车
case 'KeyA': _this.gs.tr = true; break; // 右转
case 'KeyD': _this.gs.tl = true; break; // 左转
case 'Space': // 漂移(速度>2时生效)
if (_this.gs.sp > 2 && !_this.gs.dr) {
_this.gs.dr = true;
document.getElementById('drift-status').textContent = '漂移中';
}
break;
case 'ArrowUp': _this.gs.lu = true; break; // 视角上移
case 'ArrowDown': _this.gs.ld = true; break; // 视角下移
case 'ArrowLeft': _this.gs.ll = true; break; // 视角左移
case 'ArrowRight': _this.gs.lr = true; break; // 视角右移
case 'KeyR': _this.rg(); break; // 重置游戏
}
};
// 按键抬起事件
const ku = function (e) {
switch (e.code) {
case 'KeyW': _this.gs.acc = false; break;
case 'KeyS': _this.gs.dec = false; break;
case 'KeyA': _this.gs.tr = false; _this.gs.krt = 0; break;
case 'KeyD': _this.gs.tl = false; _this.gs.klt = 0; break;
case 'Space': // 结束漂移
_this.gs.dr = false;
_this.gs.da = 0;
document.getElementById('drift-status').textContent = '正常行驶';
break;
case 'ArrowUp': _this.gs.lu = false; break;
case 'ArrowDown': _this.gs.ld = false; break;
case 'ArrowLeft': _this.gs.ll = false; break;
case 'ArrowRight': _this.gs.lr = false; break;
}
};
document.addEventListener('keydown', kd);
document.addEventListener('keyup', ku);
}
设计亮点
游戏结束状态过滤
:游戏结束后仅响应 R 键重置,避免无效操作
漂移条件判断
:只有速度 > 2 时才能触发漂移,符合真实赛车的物理逻辑
状态重置
:转向按键抬起时重置转向累积时间,避免转向角度残留
核心物理逻辑实现
物理逻辑是赛车游戏的灵魂,本文实现了轻量级的车辆物理,包含加速、减速、摩擦力、转向、漂移等核心逻辑:
- 速度与摩擦力计算
up(dt) {
if (this.gs.over) return; // 游戏结束则停止更新
// 速度更新
if (this.gs.acc) {
this.gs.sp += this.gs.ac; // 加速
this.gs.sp = Math.min(this.gs.sp, this.gs.msp); // 限制最大速度
} else if (this.gs.dec) {
this.gs.sp -= this.gs.ac; // 减速/倒车
this.gs.sp = Math.max(this.gs.sp, -this.gs.mrp); // 限制最大倒车速度
} else {
// 摩擦力 - 漂移时摩擦力更小
const fr = this.gs.dr ? this.gs.dfr : this.gs.fr;
if (Math.abs(this.gs.sp) > 0.01) {
this.gs.sp *= (1 - fr);
} else {
this.gs.sp = 0; // 速度过小时直接归零,避免抖动
}
}
// 转向逻辑...
// 位置更新...
// 动画更新...
// UI更新...
}
2. 转向逻辑(支持长按累积角度)
// 转向角度计算
let ta = 0;
const ts = this.gs.dr ? this.gs.dts : this.gs.bts; // 转向灵敏度(漂移时更高)
const sf = Math.abs(this.gs.sp) / this.gs.msp; // 速度系数(速度越快转向越灵敏)
if (this.gs.tl) {
this.gs.klt += dt; // 长按累积时间
this.gs.klt = Math.min(this.gs.klt, this.gs.mtt); // 限制最大累积时间
let tta = -ts * sf * this.gs.klt * 60; // 转向角度(弧度)
const tad = tta * (180 / Math.PI) * 10; // 转为角度(放大10倍便于显示)
const ctd = Math.max(-this.gs.mta, Math.min(tad, 0)); // 限制最大转向角
ta = ctd / 10 * (Math.PI / 180); // 转回弧度
this.gs.fwta = ta * 3; // 前轮转向角度(放大3倍增强视觉效果)
if (this.gs.dr) {
this.gs.da = Math.min(this.gs.da + 0.02, 0.3); // 漂移时车身倾斜
}
} else if (this.gs.tr) {
// 右转逻辑(与左转对称)
// ...
} else {
// 转向回正(缓动)
this.gs.fwta *= 0.8;
if (Math.abs(this.gs.fwta) < 0.001) {
this.gs.fwta = 0;
}
if (this.gs.dr) {
this.gs.da *= 0.9; // 漂移倾斜回正
}
}
// 更新车辆旋转角度
this.gs.cr += ta;
设计亮点
游戏结束状态过滤:
游戏结束后仅响应 R 键重置,避免无效操作
漂移条件判断:
只有速度 > 2 时才能触发漂移,符合真实赛车的物理逻辑
状态重置:
转向按键抬起时重置转向累积时间,避免转向角度残留 核心物理逻辑实现 物理逻辑是赛车游戏的灵魂,本文实现了轻量级的车辆物理,包含加速、减速、摩擦力、转向、漂移等核心逻辑:
1. 速度与摩擦力计算
up(dt) {
if (this.gs.over) return; // 游戏结束则停止更新
// 速度更新
if (this.gs.acc) {
this.gs.sp += this.gs.ac; // 加速
this.gs.sp = Math.min(this.gs.sp, this.gs.msp); // 限制最大速度
} else if (this.gs.dec) {
this.gs.sp -= this.gs.ac; // 减速/倒车
this.gs.sp = Math.max(this.gs.sp, -this.gs.mrp); // 限制最大倒车速度
} else {
// 摩擦力 - 漂移时摩擦力更小
const fr = this.gs.dr ? this.gs.dfr : this.gs.fr;
if (Math.abs(this.gs.sp) > 0.01) {
this.gs.sp *= (1 - fr);
} else {
this.gs.sp = 0; // 速度过小时直接归零,避免抖动
}
}
// 转向逻辑...
// 位置更新...
// 动画更新...
// UI更新...
}
2. 转向逻辑(支持长按累积角度)
// 转向角度计算
let ta = 0;
const ts = this.gs.dr ? this.gs.dts : this.gs.bts; // 转向灵敏度(漂移时更高)
const sf = Math.abs(this.gs.sp) / this.gs.msp; // 速度系数(速度越快转向越灵敏)
if (this.gs.tl) {
this.gs.klt += dt; // 长按累积时间
this.gs.klt = Math.min(this.gs.klt, this.gs.mtt); // 限制最大累积时间
let tta = -ts * sf * this.gs.klt * 60; // 转向角度(弧度)
const tad = tta * (180 / Math.PI) * 10; // 转为角度(放大10倍便于显示)
const ctd = Math.max(-this.gs.mta, Math.min(tad, 0)); // 限制最大转向角
ta = ctd / 10 * (Math.PI / 180); // 转回弧度
this.gs.fwta = ta * 3; // 前轮转向角度(放大3倍增强视觉效果)
if (this.gs.dr) {
this.gs.da = Math.min(this.gs.da + 0.02, 0.3); // 漂移时车身倾斜
}
} else if (this.gs.tr) {
// 右转逻辑(与左转对称)
// ...
} else {
// 转向回正(缓动)
this.gs.fwta *= 0.8;
if (Math.abs(this.gs.fwta) < 0.001) {
this.gs.fwta = 0;
}
if (this.gs.dr) {
this.gs.da *= 0.9; // 漂移倾斜回正
}
}
// 更新车辆旋转角度
this.gs.cr += ta;
3. 车辆位置更新
// 计算前进方向向量
const f = new THREE.Vector3(
-Math.sin(this.gs.cr),
0,
-Math.cos(this.gs.cr)
);
// 更新位置(速度 * 时间 * 转换系数)
this.c.p.x += f.x * this.gs.sp * 60 * dt;
this.c.p.z += f.z * this.gs.sp * 60 * dt;
// 赛道边界检测 - 超出赛道范围则减速
const cdc = Math.sqrt(this.c.p.x * this.c.p.x + this.c.p.z * this.c.p.z);
if (cdc > 90 || cdc < 70) {
this.gs.sp *= 0.95;
}
// 更新赛车模型位置和旋转
this.c.m.position.copy(this.c.p);
this.c.m.rotation.y = this.gs.cr;
this.c.m.rotation.z = this.gs.da; // 漂移倾斜
相机控制与 UI 交互
1. 第三人称视角跟随
upCam() {
const cd = 25; // 相机与车辆的距离
const ch = 15; // 相机高度基准值
// 计算相机位置(绕车辆旋转)
const cox = Math.sin(this.gs.cr + this.gs.mx) * cd;
const coz = Math.cos(this.gs.cr + this.gs.mx) * cd;
const cx = this.c.p.x - cox;
const cz = this.c.p.z - coz;
const cy = this.c.p.y + ch - this.gs.my * 10; // 视角上下调整
// 更新相机位置并看向车辆
this.cam.position.set(cx, cy, cz);
this.cam.lookAt(this.c.p.x, this.c.p.y + 1, this.c.p.z);
}
2. UI 实时更新
// 速度更新(基准值转km/h)
const ks = Math.round(Math.abs(this.gs.sp) * 36);
document.getElementById('speed').textContent = ks;
// 距离终点更新
const d = this.c.p.distanceTo(this.t.p);
document.getElementById('distance').textContent = Math.round(d);
// 冲线判定(距离<8米)
if (d < 8) {
this.go(true);
}
3. 冲线提示与游戏重置
// 游戏结束处理
go(suc) {
this.gs.over = true;
if (suc) {
document.getElementById('success-message').style.display = 'block';
document.getElementById('success-message').innerHTML = `
<div>冲线成功!</div>
<div style="font-size: 24px; margin-top: 20px;">恭喜完成赛道挑战!</div>
<div style="font-size: 20px; margin-top: 10px;">最终速度: ${Math.round(Math.abs(this.gs.sp)*36)} km/h</div>
<div style="font-size: 20px; margin-top: 10px;">按R键重新开始</div>
`;
} else {
// 失败提示(本文未实现失败逻辑,可扩展
总代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>2D赛道 3D赛车游戏</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
cursor: default !important;
}
body {
overflow: hidden;
background: #87CEEB;
font-family: 'SimHei', 'Microsoft YaHei', sans-serif;
}
#game-container {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
#ui {
position: fixed;
top: 20px;
left: 20px;
z-index: 100;
color: white;
text-shadow: 2px 2px 4px #000;
font-size: 18px;
}
#target-indicator {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: #FFD700;
font-size: 24px;
text-shadow: 2px 2px 4px #000;
z-index: 90;
}
#success-message {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: #FFD700;
font-size: 48px;
text-shadow: 3px 3px 6px #000;
z-index: 100;
display: none;
text-align: center;
}
.controls {
position: fixed;
bottom: 20px;
left: 20px;
color: white;
text-shadow: 1px 1px 2px #000;
font-size: 14px;
background: rgba(0,0,0,0.5);
padding: 10px;
border-radius: 5px;
}
#lock提示 {
display: none !important;
}
</style>
</head>
<body>
<div id="game-container"></div>
<div id="ui">
<div>车辆: 赛车</div>
<div>速度: <span id="speed">0</span> km/h</div>
<div>距离终点: <span id="distance">0</span>米</div>
<div>状态: <span id="drift-status">正常行驶</span></div>
<div>转向角度: <span id="turn-angle">0</span>°</div>
</div>
<div id="target-indicator">▶ 终点 ◀</div>
<div id="success-message">
<div>冲线成功!</div>
<div style="font-size: 24px; margin-top: 20px;">恭喜完成赛道挑战!</div>
<div style="font-size: 20px; margin-top: 10px;">按R键重新开始</div>
</div>
<div id="lock提示">点击屏幕锁定鼠标<br>(ESC键解锁)</div>
<div class="controls">
<div>W: 加速 | S: 减速/倒车 | A: 右转 | D: 左转 (长按角度增大,最大60°) | 方向键: 调整视角 | 空格: 漂移 | R: 重置</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/three.min.js"></script>
<script>
class Game {
constructor() {
this.s = new THREE.Scene();
this.s.fog = new THREE.Fog(0x87CEEB, 100, 400);
this.cam = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 2000);
this.cam.position.set(0, 15, 25);
this.r = new THREE.WebGLRenderer({ antialias: true, alpha: true });
this.r.setSize(window.innerWidth, window.innerHeight);
this.r.setClearColor(0x87CEEB);
this.r.shadowMap.enabled = true;
this.r.shadowMap.type = THREE.PCFSoftShadowMap;
document.getElementById('game-container').appendChild(this.r.domElement);
this.gs = {
acc: false,
dec: false,
tl: false,
tr: false,
lu: false,
ld: false,
ll: false,
lr: false,
dr: false,
vel: new THREE.Vector3(),
dir: new THREE.Vector3(),
over: false,
mx: 0,
my: 0,
ca: 0,
sp: 0,
msp: 8,
mrp: 4,
ac: 0.15,
dc: 0.1,
fr: 0.08,
dfr: 0.04,
bts: 0.02,
dts: 0.04,
da: 0,
cr: 0,
klt: 0,
krt: 0,
mtt: 1.5,
cta: 0,
mta: 60,
fwta: 0
};
this.vs = 0.03;
this.c = {
m: null,
p: new THREE.Vector3(0, 1, 0),
r: 0,
fw: [],
rw: []
};
this.t = {
m: null,
p: new THREE.Vector3(0, 0, -180)
};
this.initS();
this.initC();
this.initT();
this.initTar();
this.initCtrl();
this.lt = performance.now();
this.an();
window.addEventListener('resize', () => this.wr());
this.r.render(this.s, this.cam);
}
initS() {
const al = new THREE.AmbientLight(0xffffff, 0.7);
this.s.add(al);
const dl = new THREE.DirectionalLight(0xffffff, 0.9);
dl.position.set(50, 80, 40);
dl.castShadow = true;
dl.shadow.camera.left = -250;
dl.shadow.camera.right = 250;
dl.shadow.camera.top = 250;
dl.shadow.camera.bottom = -250;
dl.shadow.mapSize.width = 2048;
dl.shadow.mapSize.height = 2048;
this.s.add(dl);
const gg = new THREE.PlaneGeometry(600, 600, 100, 100);
const gm = new THREE.MeshStandardMaterial({
color: 0x228B22,
roughness: 0.9,
metalness: 0.1
});
const g = new THREE.Mesh(gg, gm);
g.rotation.x = -Math.PI / 2;
g.receiveShadow = true;
this.s.add(g);
}
initC() {
const cg = new THREE.Group();
const bg = new THREE.BoxGeometry(4, 1.2, 8);
const bm = new THREE.MeshStandardMaterial({ color: 0xFF0000 });
const b = new THREE.Mesh(bg, bm);
b.position.y = 0.6;
b.castShadow = true;
cg.add(b);
const cpg = new THREE.BoxGeometry(2.5, 0.8, 3);
const cpm = new THREE.MeshStandardMaterial({ color: 0x000000 });
const cp = new THREE.Mesh(cpg, cpm);
cp.position.set(0, 1.2, -1);
cg.add(cp);
const wg = new THREE.BoxGeometry(3, 0.2, 0.5);
const wm = new THREE.MeshStandardMaterial({ color: 0xFF0000 });
const w = new THREE.Mesh(wg, wm);
w.position.set(0, 1.5, 3.5);
cg.add(w);
const cw = (x, z, f = true) => {
const wg = new THREE.Group();
const tg = new THREE.CylinderGeometry(0.8, 0.8, 0.5, 16);
const tm = new THREE.MeshStandardMaterial({ color: 0x111111 });
const t = new THREE.Mesh(tg, tm);
t.rotation.z = Math.PI / 2;
t.castShadow = true;
wg.add(t);
const rg = new THREE.CylinderGeometry(0.6, 0.6, 0.4, 16);
const rm = new THREE.MeshStandardMaterial({ color: 0xCCCCCC });
const r = new THREE.Mesh(rg, rm);
r.rotation.z = Math.PI / 2;
wg.add(r);
wg.position.set(x, 0.4, z);
cg.add(wg);
return wg;
};
this.c.fw.push(cw(-2.2, 3, true));
this.c.fw.push(cw(2.2, 3, true));
this.c.rw.push(cw(-2.2, -3, false));
this.c.rw.push(cw(2.2, -3, false));
cg.position.copy(this.c.p);
this.c.m = cg;
this.s.add(this.c.m);
}
initT() {
const tg = new THREE.Group();
const tw = 12;
const trs = 80;
const tsg = 64;
const tgeo = new THREE.RingGeometry(trs - tw/2, trs + tw/2, tsg);
const tmat = new THREE.MeshStandardMaterial({
color: 0x333333,
roughness: 0.8,
metalness: 0.1,
side: THREE.DoubleSide
});
const tbase = new THREE.Mesh(tgeo, tmat);
tbase.rotation.x = -Math.PI / 2;
tbase.position.y = 0.05;
tg.add(tbase);
const op = [];
for (let i = 0; i <= tsg; i++) {
const a = (i / tsg) * Math.PI * 2;
op.push(new THREE.Vector3(
Math.cos(a) * (trs + tw/2),
0.06,
Math.sin(a) * (trs + tw/2)
));
}
const olgeo = new THREE.BufferGeometry().setFromPoints(op);
const olmat = new THREE.LineBasicMaterial({ color: 0xFFFFFF, linewidth: 2 });
const ol = new THREE.Line(olgeo, olmat);
tg.add(ol);
const ip = [];
for (let i = 0; i <= tsg; i++) {
const a = (i / tsg) * Math.PI * 2;
ip.push(new THREE.Vector3(
Math.cos(a) * (trs - tw/2),
0.06,
Math.sin(a) * (trs - tw/2)
));
}
const ilgeo = new THREE.BufferGeometry().setFromPoints(ip);
const ilmat = new THREE.LineBasicMaterial({ color: 0xFFFFFF, linewidth: 2 });
const il = new THREE.Line(ilgeo, ilmat);
tg.add(il);
const flp = [
new THREE.Vector3(-tw/2, 0.07, -trs),
new THREE.Vector3(tw/2, 0.07, -trs)
];
const flgeo = new THREE.BufferGeometry().setFromPoints(flp);
const flmat = new THREE.LineBasicMaterial({ color: 0xFFD700, linewidth: 4 });
const fl = new THREE.Line(flgeo, flmat);
tg.add(fl);
this.s.add(tg);
}
initTar() {
const tg = new THREE.ConeGeometry(3, 6, 8);
const tm = new THREE.MeshStandardMaterial({
color: 0xFFD700,
emissive: 0xFFD700,
emissiveIntensity: 0.8
});
const t = new THREE.Mesh(tg, tm);
t.position.copy(this.t.p);
t.position.y = 3;
t.castShadow = true;
this.t.m = t;
this.s.add(this.t.m);
}
initCtrl() {
const _this = this;
const kd = function (e) {
if (_this.gs.over && e.code !== 'KeyR') return;
switch (e.code) {
case 'KeyW':
_this.gs.acc = true;
break;
case 'KeyS':
_this.gs.dec = true;
break;
case 'KeyA':
_this.gs.tr = true;
break;
case 'KeyD':
_this.gs.tl = true;
break;
case 'Space':
if (_this.gs.sp > 2 && !_this.gs.dr) {
_this.gs.dr = true;
document.getElementById('drift-status').textContent = '漂移中';
}
break;
case 'ArrowUp':
_this.gs.lu = true;
break;
case 'ArrowDown':
_this.gs.ld = true;
break;
case 'ArrowLeft':
_this.gs.ll = true;
break;
case 'ArrowRight':
_this.gs.lr = true;
break;
case 'KeyR':
_this.rg();
break;
}
};
const ku = function (e) {
switch (e.code) {
case 'KeyW':
_this.gs.acc = false;
break;
case 'KeyS':
_this.gs.dec = false;
break;
case 'KeyA':
_this.gs.tr = false;
_this.gs.krt = 0;
break;
case 'KeyD':
_this.gs.tl = false;
_this.gs.klt = 0;
break;
case 'Space':
_this.gs.dr = false;
_this.gs.da = 0;
document.getElementById('drift-status').textContent = '正常行驶';
break;
case 'ArrowUp':
_this.gs.lu = false;
break;
case 'ArrowDown':
_this.gs.ld = false;
break;
case 'ArrowLeft':
_this.gs.ll = false;
break;
case 'ArrowRight':
_this.gs.lr = false;
break;
}
};
document.addEventListener('keydown', kd);
document.addEventListener('keyup', ku);
}
up(dt) {
if (this.gs.over) return;
this.uv(dt);
if (this.gs.acc) {
this.gs.sp += this.gs.ac;
this.gs.sp = Math.min(this.gs.sp, this.gs.msp);
} else if (this.gs.dec) {
this.gs.sp -= this.gs.ac;
this.gs.sp = Math.max(this.gs.sp, -this.gs.mrp);
} else {
const fr = this.gs.dr ? this.gs.dfr : this.gs.fr;
if (Math.abs(this.gs.sp) > 0.01) {
this.gs.sp *= (1 - fr);
} else {
this.gs.sp = 0;
}
}
let ta = 0;
const ts = this.gs.dr ? this.gs.dts : this.gs.bts;
const sf = Math.abs(this.gs.sp) / this.gs.msp;
if (this.gs.tl) {
this.gs.klt += dt;
this.gs.klt = Math.min(this.gs.klt, this.gs.mtt);
let tta = -ts * sf * this.gs.klt * 60;
const tad = tta * (180 / Math.PI) * 10;
const ctd = Math.max(-this.gs.mta, Math.min(tad, 0));
ta = ctd / 10 * (Math.PI / 180);
this.gs.fwta = ta * 3;
if (this.gs.dr) {
this.gs.da = Math.min(this.gs.da + 0.02, 0.3);
}
} else if (this.gs.tr) {
this.gs.krt += dt;
this.gs.krt = Math.min(this.gs.krt, this.gs.mtt);
let tta = ts * sf * this.gs.krt * 60;
const tad = tta * (180 / Math.PI) * 10;
const ctd = Math.min(this.gs.mta, Math.max(tad, 0));
ta = ctd / 10 * (Math.PI / 180);
this.gs.fwta = ta * 3;
if (this.gs.dr) {
this.gs.da = Math.max(this.gs.da - 0.02, -0.3);
}
} else {
this.gs.fwta *= 0.8;
if (Math.abs(this.gs.fwta) < 0.001) {
this.gs.fwta = 0;
}
if (this.gs.dr) {
this.gs.da *= 0.9;
}
}
this.gs.cta = Math.min(
this.gs.mta,
Math.max(-this.gs.mta, ta * (180 / Math.PI) * 10)
);
document.getElementById('turn-angle').textContent = Math.round(Math.abs(this.gs.cta));
this.gs.cr += ta;
const f = new THREE.Vector3(
-Math.sin(this.gs.cr),
0,
-Math.cos(this.gs.cr)
);
this.c.p.x += f.x * this.gs.sp * 60 * dt;
this.c.p.z += f.z * this.gs.sp * 60 * dt;
const cdc = Math.sqrt(this.c.p.x * this.c.p.x + this.c.p.z * this.c.p.z);
if (cdc > 90 || cdc < 70) {
this.gs.sp *= 0.95;
}
this.c.m.position.copy(this.c.p);
this.c.m.rotation.y = this.gs.cr;
this.c.m.rotation.z = this.gs.da;
const wrs = this.gs.sp * 2;
this.c.fw.forEach(w => {
w.rotation.x += wrs * dt * 60;
w.rotation.y = this.gs.fwta;
});
this.c.rw.forEach(w => {
w.rotation.x += wrs * dt * 60;
});
this.upCam();
const ks = Math.round(Math.abs(this.gs.sp) * 36);
document.getElementById('speed').textContent = ks;
const d = this.c.p.distanceTo(this.t.p);
document.getElementById('distance').textContent = Math.round(d);
if (d < 8) {
this.go(true);
}
}
uv(dt) {
if (this.gs.lu) {
this.gs.my -= this.vs * dt * 60;
}
if (this.gs.ld) {
this.gs.my += this.vs * dt * 60;
}
if (this.gs.ll) {
this.gs.mx -= this.vs * dt * 60;
}
if (this.gs.lr) {
this.gs.mx += this.vs * dt * 60;
}
this.gs.my = Math.max(-Math.PI/2, Math.min(Math.PI/2, this.gs.my));
}
upCam() {
const cd = 25;
const ch = 15;
const cox = Math.sin(this.gs.cr + this.gs.mx) * cd;
const coz = Math.cos(this.gs.cr + this.gs.mx) * cd;
const cx = this.c.p.x - cox;
const cz = this.c.p.z - coz;
const cy = this.c.p.y + ch - this.gs.my * 10;
this.cam.position.set(cx, cy, cz);
this.cam.lookAt(this.c.p.x, this.c.p.y + 1, this.c.p.z);
}
go(suc) {
this.gs.over = true;
if (suc) {
document.getElementById('success-message').style.display = 'block';
document.getElementById('success-message').innerHTML = `
<div>冲线成功!</div>
<div style="font-size: 24px; margin-top: 20px;">恭喜完成赛道挑战!</div>
<div style="font-size: 20px; margin-top: 10px;">最终速度: ${Math.round(Math.abs(this.gs.sp)*36)} km/h</div>
<div style="font-size: 20px; margin-top: 10px;">按R键重新开始</div>
`;
} else {
document.getElementById('success-message').style.display = 'block';
document.getElementById('success-message').innerHTML = `
<div>挑战失败</div>
<div style="font-size: 24px; margin-top: 20px;">请重新尝试!</div>
<div style="font-size: 20px; margin-top: 10px;">按R键重新开始</div>
`;
}
}
rg() {
this.gs = {
acc: false,
dec: false,
tl: false,
tr: false,
lu: false,
ld: false,
ll: false,
lr: false,
dr: false,
vel: new THREE.Vector3(),
dir: new THREE.Vector3(),
over: false,
mx: 0,
my: 0,
ca: 0,
sp: 0,
msp: 8,
mrp: 4,
ac: 0.15,
dc: 0.1,
fr: 0.08,
dfr: 0.04,
bts: 0.02,
dts: 0.04,
da: 0,
cr: 0,
klt: 0,
krt: 0,
mtt: 1.5,
cta: 0,
mta: 60,
fwta: 0
};
this.c.fw.forEach(w => {
w.rotation.y = 0;
});
this.c.p.set(0, 1, 0);
this.c.r = 0;
this.cam.position.set(0, 15, 25);
document.getElementById('speed').textContent = 0;
document.getElementById('distance').textContent = 0;
document.getElementById('drift-status').textContent = '正常行驶';
document.getElementById('turn-angle').textContent = 0;
document.getElementById('success-message').style.display = 'none';
}
wr() {
this.cam.aspect = window.innerWidth / window.innerHeight;
this.cam.updateProjectionMatrix();
this.r.setSize(window.innerWidth, window.innerHeight);
}
an() {
requestAnimationFrame(() => this.an());
const ct = performance.now();
const dt = Math.min(0.016, (ct - this.lt) / 1000);
this.lt = ct;
this.up(dt);
this.r.render(this.s, this.cam);
}
}
document.addEventListener('DOMContentLoaded', () => {
try {
const g = new Game();
console.log('3D赛车游戏初始化成功');
} catch (err) {
console.error('游戏初始化失败:', err);
}
});
window.addEventListener('load', () => {
if (document.querySelector('canvas')) {
const cv = document.querySelector('canvas');
if (cv.getContext('webgl')) {
console.log('WebGL渲染上下文已就绪');
}
}
});
</script>
</body>
</html>
附录
本文使用ai进行文本润色,代码编写