playcanvas
PlayCanvas 是一款使用 HTML5 和 WebGL 技术运行游戏以及其他 3D 内容的开源游戏引擎,PlayCanvas 以其独特的性能实现了在任何手机移动端和桌面浏览器端均可以流畅运行。
对于开发者来说,可以在playcanvas的平台进行开发,也可以在本地开发。
官方文档 | 官方实例 | GitHub仓库
起步
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
| <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>PlayCanvas Hello Cube</title> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no" /> <style> body { margin: 0; overflow: hidden; } </style> <script src="https://code.playcanvas.com/playcanvas-stable.min.js"></script> </head> <body> <canvas id="application"></canvas> <script> const canvas = document.getElementById("application"); const app = new pc.Application(canvas);
app.setCanvasFillMode(pc.FILLMODE_FILL_WINDOW); app.setCanvasResolution(pc.RESOLUTION_AUTO);
window.addEventListener("resize", () => app.resizeCanvas());
const box = new pc.Entity("cube"); box.addComponent("model", { type: "box", }); app.root.addChild(box);
const camera = new pc.Entity("camera"); camera.addComponent("camera", { clearColor: new pc.Color(0.1, 0.1, 0.1), }); app.root.addChild(camera); camera.setPosition(0, 0, 3);
const light = new pc.Entity("light"); light.addComponent("light"); app.root.addChild(light); light.setEulerAngles(45, 0, 0);
let x,z,count = 0; app.on("update", (dt) => { count += dt; x = 3 * Math.sin(count); z = 3 * Math.cos(count); camera.setPosition(x, 0, z); camera.rotate(0,57.265*dt,0); }); app.start(); </script> </body> </html>
|
2D平面
在三维空间中一般放置立体模型,而传统web前端开发中的按钮、盒子等都会放在三维空间中创建的2D平面。例如我们在浏览器中玩3D游戏时,人物、场景只是模型,而我们操作的是在2D平面上的按钮等。
创建2D平面
| const screen = new pc.Entity(); screen.addComponent("screen", { referenceResolution: new pc.Vec2(1280, 720), scaleBlend: 0.5, scaleMode: pc.SCALEMODE_BLEND, screenSpace: true, }); app.root.addChild(screen);
|
2D平面的定位问题
文档地址
物理性质
在三维空间中引入的模型默认不具有物理性质,需要引入ammo.js才能添加重力等物理性质。主要是rigidbody
和collision
两个组件
添加物理性质
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| const floor = new pc.Entity(); floor.addComponent("render", { type: "box", material: gray, });
floor.setLocalScale(12, 0.1, 16);
floor.addComponent("rigidbody", { type: "static", restitution: 0.5, });
floor.addComponent("collision", { type: "box", halfExtents: new pc.Vec3(10, 0.1, 16), });
app.root.addChild(floor);
|
做的小玩具
BitterGourd的github仓库