UNPKG

ggabcd-meshwalk

Version:

MeshWalk.js is a JS library which helps your TPS game development with three.js.

110 lines (90 loc) 3.07 kB
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>=^.^=</title> <style> body{margin: 0; background: #000;} canvas{display: block;} .info{ color: #fff; position: absolute; top: 0; left: 0; } </style> </head> <body> <div class="info"> The red sphere as a player character will just fall down to the ground mesh. <button onclick="playerController.center.set( 0, 10, 0 );">retry</button> </div> <script type="module"> import * as THREE from 'https://unpkg.com/three@0.120.0/build/three.module.js'; import * as MW from '../dist/meshwalk.module.js'; MW.install( THREE ); // make the world, const world = new MW.World(); // then make a octree object, // which will be the container of rigid objects such as terrain const min = new THREE.Vector3( - 15, - 15, - 15 ); const max = new THREE.Vector3( 15, 15, 15 ); const partition = 5; // min and max is for the size of the octree box // see http://en.wikipedia.org/wiki/Octree // // +------+------+ // |\ \ \ // | +------+------+ // + |\ \ \ // |\| +------+------+ <-coords of max // | + | | | // coords of min-> + |\| | | // \| +------+------+ // + | | | // y \| | | // | +------+------+ // +--x // \ // z // const region = new MW.Octree( min, max, partition ); world.add( region ); const width = window.innerWidth; const height = window.innerHeight; const clock = new THREE.Clock(); const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera( 40, width / height, 1, 1000 ); camera.position.set( 0, 5, 30 ); const renderer = new THREE.WebGLRenderer(); renderer.setSize( width, height ); document.body.appendChild( renderer.domElement ); // make a terrain in three.js and import it to the octree const ground = new THREE.Mesh( new THREE.PlaneBufferGeometry( 30, 30, 10, 10 ), new THREE.MeshBasicMaterial( { color: 0xffffff, wireframe: true } ) ); ground.rotation.x = THREE.Math.degToRad( -90 ); scene.add( ground ); region.importThreeMesh( ground ); const playerRadius = 1; const playerObjectHolder = new THREE.Object3D(); playerObjectHolder.position.set( 0, 10, 0 ); scene.add( playerObjectHolder ); // make your player character const sphere = new THREE.Mesh( new THREE.SphereGeometry( playerRadius, 16, 16 ), new THREE.MeshBasicMaterial( { color: 0xff0000, wireframe: true} ) ); playerObjectHolder.add( sphere ); // to apply fake gravity and to be controllable object const playerController = new MW.CharacterController( playerObjectHolder, playerRadius ); world.add( playerController ); ( function update () { const delta = clock.getDelta(); requestAnimationFrame( update ); world.step( Math.min( delta, 0.02 ) ); renderer.render( scene, camera ); } )(); </script> </body> </html>