JavaScript系列(49)--游戏引擎实现详解
JavaScript游戏引擎实现详解 🎮
今天,让我们深入探讨JavaScript的游戏引擎实现。游戏引擎是一个复杂的系统,它需要处理渲染、物理、音频、输入等多个方面,让我们一步步实现一个基础但功能完整的游戏引擎。
游戏引擎基础概念 🌟
💡 小知识:游戏引擎是一个为游戏开发提供核心功能的框架,它通常包括渲染系统、物理引擎、音频系统、输入处理、资源管理等模块。通过合理的架构设计,这些模块可以协同工作,为游戏开发提供强大的支持。
基本实现 📊
// 1. 游戏引擎核心
class GameEngine {constructor(canvas) {this.canvas = canvas;this.context = canvas.getContext('2d');// 核心系统this.renderer = new Renderer(this.context);this.physics = new PhysicsSystem();this.input = new InputManager();this.audio = new AudioSystem();// 游戏状态this.scenes = new Map();this.currentScene = null;this.isRunning = false;// 时间管理this.lastTime = 0;this.deltaTime = 0;}// 初始化引擎init() {this.input.init();this.audio.init();window.requestAnimationFrame(this.gameLoop.bind(this));}// 游戏主循环gameLoop(timestamp) {// 计算时间增量this.deltaTime = (timestamp - this.lastTime) / 1000;this.lastTime = timestamp;if (this.isRunning && this.currentScene) {this.update();this.render();}window.requestAnimationFrame(this.gameLoop.bind(this));}// 更新游戏状态update() {this.physics.update(this.deltaTime);this.currentScene.update(this.deltaTime);this.input.update();}// 渲染游戏画面render() {this.context.clearRect(0, 0,this.canvas.width,this.canvas.height);this.currentScene.render(this.renderer);}// 场景管理addScene(name, scene) {this.scenes.set(name, scene);}loadScene(name) {const scene = this.scenes.get(name);if (scene) {if (this.currentScene) {this.currentScene.onExit();}this.currentScene = scene;scene.onEnter();}}
}// 2. 渲染系统
class Renderer {constructor(context) {this.context = context;this.camera = new Camera();}// 绘制精灵drawSprite(sprite) {const { position, scale, rotation } = sprite.transform;const { texture, width, height } = sprite;this.context.save();// 应用相机变换this.context.translate(-this.camera.position.x,-this.camera.position.y);// 应用精灵变换this.context.translate(position.x, position.y);this.context.rotate(rotation);this.context.scale(scale.x, scale.y);// 绘制精灵this.context.drawImage(texture,-width / 2,-height / 2,width,height);this.context.restore();}// 绘制图元drawPrimitive(primitive) {this.context.save();this.context.fillStyle = primitive.color;this.context.beginPath();switch (primitive.type) {case 'rectangle':this.context.fillRect(primitive.x,primitive.y,primitive.width,primitive.height);break;case 'circle':this.context.arc(primitive.x,primitive.y,primitive.radius,0,Math.PI * 2);this.context.fill();break;}this.context.restore();}
}// 3. 物理系统
class PhysicsSystem {constructor() {this.bodies = [];this.gravity = new Vector2(0, 9.81);}addBody(body) {this.bodies.push(body);}removeBody(body) {const index = this.bodies.indexOf(body);if (index !== -1) {this.bodies.splice(index, 1);}}update(deltaTime) {// 更新物理体for (const body of this.bodies) {if (!body.isStatic) {// 应用重力body.velocity.add(Vector2.multiply(this.gravity, deltaTime));// 更新位置body.position.add(Vector2.multiply(body.velocity, deltaTime));}}// 碰撞检测和处理this.detectCollisions();}detectCollisions() {for (let i = 0; i < this.bodies.length; i++) {for (let j = i + 1; j < this.bodies.length; j++) {const bodyA = this.bodies[i];const bodyB = this.bodies[j];if (this.checkCollision(bodyA, bodyB)) {this.resolveCollision(bodyA, bodyB);}}}}
}
高级功能实现 🚀
// 1. 实体组件系统
class Entity {constructor() {this.components = new Map();this.id = Entity.nextId++;}addComponent(component) {component.entity = this;this.components.set(component.constructor, component);}getComponent(componentClass) {return this.components.get(componentClass);}removeComponent(componentClass) {const component = this.components.get(componentClass);if (component) {component.entity = null;this.components.delete(componentClass);}}update(deltaTime) {for (const component of this.components.values()) {if (component.update) {component.update(deltaTime);}}}
}// 2. 组件系统
class Component {constructor() {this.entity = null;}// 生命周期方法onAdd() {}onRemove() {}update(deltaTime) {}
}class TransformComponent extends Component {constructor() {super();this.position = new Vector2();this.rotation = 0;this.scale = new Vector2(1, 1);}
}class SpriteComponent extends Component {constructor(texture) {super();this.texture = texture;this.width = texture.width;this.height = texture.height;}render(renderer) {const transform = this.entity.getComponent(TransformComponent);if (transform) {renderer.drawSprite({texture: this.texture,width: this.width,height: this.height,transform});}}
}// 3. 场景管理
class Scene {constructor() {this.entities = new Set();this.systems = new Map();}addEntity(entity) {this.entities.add(entity);}removeEntity(entity) {this.entities.delete(entity);}addSystem(system) {system.scene = this;this.systems.set(system.constructor, system);}update(deltaTime) {// 更新所有系统for (const system of this.systems.values()) {system.update(deltaTime);}// 更新所有实体for (const entity of this.entities) {entity.update(deltaTime);}}render(renderer) {for (const entity of this.entities) {const sprite = entity.getComponent(SpriteComponent);if (sprite) {sprite.render(renderer);}}}// 场景生命周期onEnter() {}onExit() {}
}
实际应用场景 💼
// 1. 游戏对象实现
class GameObject extends Entity {constructor(x = 0, y = 0) {super();// 添加基本组件const transform = new TransformComponent();transform.position.set(x, y);this.addComponent(transform);}// 便捷方法setPosition(x, y) {const transform = this.getComponent(TransformComponent);transform.position.set(x, y);}setRotation(angle) {const transform = this.getComponent(TransformComponent);transform.rotation = angle;}setScale(x, y) {const transform = this.getComponent(TransformComponent);transform.scale.set(x, y);}
}// 2. 游戏角色实现
class Player extends GameObject {constructor(x, y) {super(x, y);// 添加精灵组件const sprite = new SpriteComponent(ResourceManager.getTexture('player'));this.addComponent(sprite);// 添加物理组件const physics = new PhysicsComponent();physics.mass = 1;physics.friction = 0.1;this.addComponent(physics);// 添加输入组件const input = new InputComponent();input.bindKey('ArrowLeft', this.moveLeft.bind(this));input.bindKey('ArrowRight', this.moveRight.bind(this));input.bindKey('Space', this.jump.bind(this));this.addComponent(input);}moveLeft() {const physics = this.getComponent(PhysicsComponent);physics.applyForce(new Vector2(-100, 0));}moveRight() {const physics = this.getComponent(PhysicsComponent);physics.applyForce(new Vector2(100, 0));}jump() {const physics = this.getComponent(PhysicsComponent);if (physics.isGrounded) {physics.applyImpulse(new Vector2(0, -200));}}
}// 3. 游戏关卡实现
class GameLevel extends Scene {constructor() {super();// 创建玩家const player = new Player(100, 100);this.addEntity(player);// 创建平台this.createPlatform(0, 500, 800, 20);this.createPlatform(300, 400, 200, 20);this.createPlatform(100, 300, 200, 20);// 添加系统this.addSystem(new PhysicsSystem());this.addSystem(new CollisionSystem());this.addSystem(new RenderSystem());}createPlatform(x, y, width, height) {const platform = new GameObject(x, y);const sprite = new SpriteComponent(ResourceManager.getTexture('platform'));sprite.width = width;sprite.height = height;platform.addComponent(sprite);const physics = new PhysicsComponent();physics.isStatic = true;physics.setBox(width, height);platform.addComponent(physics);this.addEntity(platform);}
}
性能优化技巧 ⚡
// 1. 对象池系统
class ObjectPool {constructor(factory, initialSize = 10) {this.factory = factory;this.activeObjects = new Set();this.inactiveObjects = [];// 预创建对象for (let i = 0; i < initialSize; i++) {this.inactiveObjects.push(this.factory());}}spawn(x, y) {let object;if (this.inactiveObjects.length > 0) {object = this.inactiveObjects.pop();} else {object = this.factory();}object.setPosition(x, y);this.activeObjects.add(object);return object;}despawn(object) {if (this.activeObjects.has(object)) {this.activeObjects.delete(object);this.inactiveObjects.push(object);}}update(deltaTime) {for (const object of this.activeObjects) {object.update(deltaTime);}}
}// 2. 四叉树空间分区
class QuadTree {constructor(bounds, maxObjects = 10, maxLevels = 4, level = 0) {this.bounds = bounds;this.maxObjects = maxObjects;this.maxLevels = maxLevels;this.level = level;this.objects = [];this.nodes = [];}clear() {this.objects = [];for (let i = 0; i < this.nodes.length; i++) {if (this.nodes[i]) {this.nodes[i].clear();this.nodes[i] = null;}}}split() {const subWidth = this.bounds.width / 2;const subHeight = this.bounds.height / 2;const x = this.bounds.x;const y = this.bounds.y;this.nodes[0] = new QuadTree({x: x + subWidth,y: y,width: subWidth,height: subHeight}, this.maxObjects, this.maxLevels, this.level + 1);this.nodes[1] = new QuadTree({x: x,y: y,width: subWidth,height: subHeight}, this.maxObjects, this.maxLevels, this.level + 1);this.nodes[2] = new QuadTree({x: x,y: y + subHeight,width: subWidth,height: subHeight}, this.maxObjects, this.maxLevels, this.level + 1);this.nodes[3] = new QuadTree({x: x + subWidth,y: y + subHeight,width: subWidth,height: subHeight}, this.maxObjects, this.maxLevels, this.level + 1);}getIndex(rect) {const verticalMidpoint = this.bounds.x + (this.bounds.width / 2);const horizontalMidpoint = this.bounds.y + (this.bounds.height / 2);const topQuadrant = (rect.y < horizontalMidpoint && rect.y + rect.height < horizontalMidpoint);const bottomQuadrant = (rect.y > horizontalMidpoint);if (rect.x < verticalMidpoint && rect.x + rect.width < verticalMidpoint) {if (topQuadrant) {return 1;} else if (bottomQuadrant) {return 2;}} else if (rect.x > verticalMidpoint) {if (topQuadrant) {return 0;} else if (bottomQuadrant) {return 3;}}return -1;}
}// 3. 渲染优化
class RenderOptimizer {constructor(renderer) {this.renderer = renderer;this.visibleObjects = new Set();this.frustum = new Frustum();}updateVisibility(camera, objects) {this.visibleObjects.clear();this.frustum.updateFromCamera(camera);for (const object of objects) {if (this.frustum.intersectsBox(object.getBoundingBox())) {this.visibleObjects.add(object);}}}render() {// 按材质排序const sortedObjects = Array.from(this.visibleObjects).sort((a, b) => a.material.id - b.material.id);// 批量渲染let currentMaterial = null;for (const object of sortedObjects) {if (object.material !== currentMaterial) {currentMaterial = object.material;this.renderer.setMaterial(currentMaterial);}this.renderer.renderObject(object);}}
}
最佳实践建议 💡
- 游戏引擎架构设计
// 1. 模块化设计
class GameModule {constructor(engine) {this.engine = engine;}init() {}update(deltaTime) {}destroy() {}
}// 2. 事件系统
class EventSystem extends GameModule {constructor(engine) {super(engine);this.listeners = new Map();}on(event, callback) {if (!this.listeners.has(event)) {this.listeners.set(event, new Set());}this.listeners.get(event).add(callback);}off(event, callback) {const callbacks = this.listeners.get(event);if (callbacks) {callbacks.delete(callback);}}emit(event, data) {const callbacks = this.listeners.get(event);if (callbacks) {for (const callback of callbacks) {callback(data);}}}
}// 3. 资源管理
class ResourceManager extends GameModule {constructor(engine) {super(engine);this.resources = new Map();this.loading = new Map();}async load(url, type) {if (this.resources.has(url)) {return this.resources.get(url);}if (this.loading.has(url)) {return this.loading.get(url);}const loadPromise = this.loadResource(url, type);this.loading.set(url, loadPromise);try {const resource = await loadPromise;this.resources.set(url, resource);this.loading.delete(url);return resource;} catch (error) {this.loading.delete(url);throw error;}}async loadResource(url, type) {switch (type) {case 'image':return this.loadImage(url);case 'audio':return this.loadAudio(url);case 'json':return this.loadJSON(url);default:throw new Error(`Unsupported resource type: ${type}`);}}
}
结语 📝
JavaScript游戏引擎的实现是一个复杂但有趣的主题。通过本文,我们学习了:
- 游戏引擎的基本架构和核心系统
- 实体组件系统的实现
- 场景管理和游戏对象
- 性能优化技巧
- 最佳实践和设计模式
💡 学习建议:在实现游戏引擎时,要注意模块之间的解耦和性能优化。合理使用设计模式和优化策略,可以显著提升游戏的运行效率。
如果你觉得这篇文章有帮助,欢迎点赞收藏,也期待在评论区看到你的想法和建议!👇
终身学习,共同成长。
咱们下一期见
💻
相关文章:
JavaScript系列(49)--游戏引擎实现详解
JavaScript游戏引擎实现详解 🎮 今天,让我们深入探讨JavaScript的游戏引擎实现。游戏引擎是一个复杂的系统,它需要处理渲染、物理、音频、输入等多个方面,让我们一步步实现一个基础但功能完整的游戏引擎。 游戏引擎基础概念 &am…...
AI如何帮助解决生活中的琐碎难题?
引言:AI已经融入我们的日常生活 你有没有遇到过这样的情况——早上匆忙出门却忘了带钥匙,到了公司才想起昨天的会议资料没有打印,或者下班回家还在纠结晚饭吃什么?这些看似微不足道的小事,往往让人疲惫不堪。而如今&a…...
K8s运维管理平台 - KubeSphere 3.x 和4.x 使用分析:功能较强,UI美观
目录标题 Lic使用感受优点:优化点: 实操首页项目 | 应用负载 | 配置 | 定制资源定义存储监控告警集群设置 **KubeSphere 3.x** 和 **4.x**1. **架构变化**:2. **多集群管理**:3. **增强的 DevOps 功能**:4. **监控与日…...
芯片AI深度实战:基础篇之langchain
基于ollama, langchain,可以构建一个自己的知识库,比如这个 Build Your Own RAG App: A Step-by-Step Guide to Setup LLM locally using Ollama, Python, and ChromaDB | HackerNoon 这是因为: 以上范例就实现了这样一个流程: 系列文章&…...
WordPress使用(1)
1. 概述 WordPress是一个开源博客框架,配合不同主题,可以有多种展现方式,博客、企业官网、CMS系统等,都可以很好的实现。 官网:博客工具、发布平台和内容管理系统 – WordPress.org China 简体中文,这里可…...
单机伪分布Hadoop详细配置
目录 1. 引言2. 配置单机Hadoop2.1 下载并解压JDK1.8、Hadoop3.3.62.2 配置环境变量2.3 验证JDK、Hadoop配置 3. 伪分布Hadoop3.1 配置ssh免密码登录3.2 配置伪分布Hadoop3.2.1 修改hadoop-env.sh3.2.2 修改core-site.xml3.2.3 修改hdfs-site.xml3.2.4 修改yarn-site.xml3.2.5 …...
【高内聚】设计模式是如何让软件更好做到高内聚的?
高内聚(High Cohesion)是指模块内部的元素紧密协作,共同完成一个明确且相对独立的功能。就像高效的小团队,成员们目标一致,相互配合默契。 低耦合(Loose Coupling)是指模块之间的依赖较少&#…...
10.2 目录(文件夹)操作
版权声明:本文为博主原创文章,转载请在显著位置标明本文出处以及作者网名,未经作者允许不得用于商业目的。 10.2.1 DirectoryInfo类 DirectoryInfo类可以获得目录信息。 DirectoryInfo常用属性: Name:获取Director…...
LiteFlow Spring boot使用方式
文章目录 概述LiteFlow框架的优势规则调用逻辑规则组件定义组件内数据获取通过 DefaultContext自定义上下文 通过 组件规则定义数据通过预先传入数据 liteflow 使用 概述 在每个公司的系统中,总有一些拥有复杂业务逻辑的系统,这些系统承载着核心业务逻…...
OSCP:Windows 服务提权详解
在Windows操作系统中,服务是一种特殊的后台进程,它们通常以较高的权限(如 SYSTEM 或 Administrator)运行。攻击者可以通过控制服务的创建、配置或运行过程实现权限提升(提权)。本文将详细分析Windows服务提…...
星火大模型接入及文本生成HTTP流式、非流式接口(JAVA)
文章目录 一、接入星火大模型二、基于JAVA实现HTTP非流式接口1.配置2.接口实现(1)分析接口请求(2)代码实现 3.功能测试(1)测试对话功能(2)测试记住上下文功能 三、基于JAVA实现HTTP流…...
21.Word:小赵-毕业论文排版❗【39】
目录 题目 NO1.2 NO3.4 NO5.6 NO7.8.9 NO10.11.12 题目 NO1.2 自己的论文当中接收老师的修改:审阅→比较→源文档:考生文件夹:Word.docx→修订的文档:考生文件夹:教师修改→确定→接收→接收所有修订将合并之…...
Python中的函数(上)
Python中的函数是非常重要的编程概念,以下是详细的介绍: 函数定义基础 在Python中,函数是组织好的、可重复使用的代码块,用于执行特定任务。通过函数,我们可以将复杂的程序分解为较小的、更易管理的部分,…...
Windows11 安装poetry
使用powershell安装 (Invoke-WebRequest -Uri https://install.python-poetry.org -UseBasicParsing).Content | py - 如果使用py运行失败则替换为python即可 终端运行结果如下 D:\AI\A_Share_investment_Agent> (Invoke-WebRequest -Uri https://install.python-poetry.…...
浅谈Linux 权限、压缩、进程与服务
概述 放假回家,对Linux系统的一些知识进行重新的整理,做到温故而知新,对用户权限管理、文件赋权、压缩文件、进程与服务的知识进行了一次梳理和总结。 权限管理 Linux最基础的权限是用户和文件,先了解基础的用户权限和文件权限…...
006 LocalStorage和SessionStorage
JWT存储在LocalStorage与SessionStorage里的区别和共同点如下: 区别 数据有效期: • LocalStorage:始终有效,存储的数据会一直保留在浏览器中,即使窗口或浏览器关闭也一直保存,因此常用作持久数据。 • Se…...
AJAX RSS Reader:技术解析与应用场景
AJAX RSS Reader:技术解析与应用场景 引言 随着互联网的快速发展,信息量呈爆炸式增长。为了方便用户快速获取感兴趣的信息,RSS(Really Simple Syndication)技术应运而生。AJAX RSS Reader作为一种基于AJAX技术的信息读取工具,在用户体验和信息获取方面具有显著优势。本…...
Go优雅实现redis分布式锁
前言 系统为了保证高可用,通常会部署多实例,并且会存在同时对共享资源并发读写,这时候为了保证读写的安全,常规手段是会引入分布式锁,本文将介绍如何使用redis设计一个优雅的Go分布式锁。 设计 redis分布式锁是借助…...
本地部署deepseek模型步骤
文章目录 0.deepseek简介1.安装ollama软件2.配置合适的deepseek模型3.安装chatbox可视化 0.deepseek简介 DeepSeek 是一家专注于人工智能技术研发的公司,致力于打造高性能、低成本的 AI 模型,其目标是让 AI 技术更加普惠,让更多人能够用上强…...
(2025 年最新)MacOS Redis Desktop Manager中文版下载,附详细图文
MacOS Redis Desktop Manager中文版下载 大家好,今天给大家带来一款非常实用的 Redis 可视化工具——Redis Desktop Manager(简称 RDM)。相信很多开发者都用过 Redis 数据库,但如果你想要更高效、更方便地管理 Redis 数据&#x…...
CTF show Web 红包题第六弹
提示 1.不是SQL注入 2.需要找关键源码 思路 进入页面发现是一个登录框,很难让人不联想到SQL注入,但提示都说了不是SQL注入,所以就不往这方面想了 先查看一下网页源码,发现一段JavaScript代码,有一个关键类ctfs…...
vscode(仍待补充)
写于2025 6.9 主包将加入vscode这个更权威的圈子 vscode的基本使用 侧边栏 vscode还能连接ssh? debug时使用的launch文件 1.task.json {"tasks": [{"type": "cppbuild","label": "C/C: gcc.exe 生成活动文件"…...
Linux云原生安全:零信任架构与机密计算
Linux云原生安全:零信任架构与机密计算 构建坚不可摧的云原生防御体系 引言:云原生安全的范式革命 随着云原生技术的普及,安全边界正在从传统的网络边界向工作负载内部转移。Gartner预测,到2025年,零信任架构将成为超…...
04-初识css
一、css样式引入 1.1.内部样式 <div style"width: 100px;"></div>1.2.外部样式 1.2.1.外部样式1 <style>.aa {width: 100px;} </style> <div class"aa"></div>1.2.2.外部样式2 <!-- rel内表面引入的是style样…...
Mysql中select查询语句的执行过程
目录 1、介绍 1.1、组件介绍 1.2、Sql执行顺序 2、执行流程 2.1. 连接与认证 2.2. 查询缓存 2.3. 语法解析(Parser) 2.4、执行sql 1. 预处理(Preprocessor) 2. 查询优化器(Optimizer) 3. 执行器…...
基于 TAPD 进行项目管理
起因 自己写了个小工具,仓库用的Github。之前在用markdown进行需求管理,现在随着功能的增加,感觉有点难以管理了,所以用TAPD这个工具进行需求、Bug管理。 操作流程 注册 TAPD,需要提供一个企业名新建一个项目&#…...
嵌入式学习笔记DAY33(网络编程——TCP)
一、网络架构 C/S (client/server 客户端/服务器):由客户端和服务器端两个部分组成。客户端通常是用户使用的应用程序,负责提供用户界面和交互逻辑 ,接收用户输入,向服务器发送请求,并展示服务…...
2025年渗透测试面试题总结-腾讯[实习]科恩实验室-安全工程师(题目+回答)
安全领域各种资源,学习文档,以及工具分享、前沿信息分享、POC、EXP分享。不定期分享各种好玩的项目及好用的工具,欢迎关注。 目录 腾讯[实习]科恩实验室-安全工程师 一、网络与协议 1. TCP三次握手 2. SYN扫描原理 3. HTTPS证书机制 二…...
BLEU评分:机器翻译质量评估的黄金标准
BLEU评分:机器翻译质量评估的黄金标准 1. 引言 在自然语言处理(NLP)领域,衡量一个机器翻译模型的性能至关重要。BLEU (Bilingual Evaluation Understudy) 作为一种自动化评估指标,自2002年由IBM的Kishore Papineni等人提出以来,…...
Python 实现 Web 静态服务器(HTTP 协议)
目录 一、在本地启动 HTTP 服务器1. Windows 下安装 node.js1)下载安装包2)配置环境变量3)安装镜像4)node.js 的常用命令 2. 安装 http-server 服务3. 使用 http-server 开启服务1)使用 http-server2)详解 …...
