ggabcd-meshwalk
Version:
MeshWalk.js is a JS library which helps your TPS game development with three.js.
108 lines (84 loc) • 3.03 kB
HTML
<html>
<head>
<meta charset="utf-8">
<title>=^.^=</title>
<style>
body{margin: 0;padding: 0; background: #000;}
canvas{display: block;}
.info{
color: #fff;
position: absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<div class="info">
WASD to move, Space to jump<br>
<button onclick="removeBox();">remove box collision</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';
// See demo/1_getstarted.html first
MW.install( THREE );
const world = new MW.World();
const min = new THREE.Vector3( -15, -15, -15 );
const max = new THREE.Vector3( 15, 15, 15 );
const partition = 2;
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 );
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 wall = new THREE.Mesh(
new THREE.BoxGeometry( 5, 6, 10 ),
new THREE.MeshNormalMaterial( { wireframe: true } )
);
wall.position.set( 0, 3, 0 );
// wall.rotation.set( 0, 0, THREE.Math.degToRad( 20 ) );
scene.add( wall );
region.importThreeMesh( wall );
window.removeBox = () => region.removeThreeMesh( wall.geometry.uuid );
const playerRadius = 1;
const playerObjectHolder = new THREE.Object3D();
playerObjectHolder.position.set( 0, 10, 0 );
scene.add( playerObjectHolder );
const sphere = new THREE.Mesh(
new THREE.SphereGeometry( playerRadius, 16, 16 ),
new THREE.MeshBasicMaterial( { color: 0xff0000, wireframe: true} )
);
playerObjectHolder.add( sphere );
const playerController = new MW.CharacterController( playerObjectHolder, playerRadius );
world.add( playerController );
// make a keyinput control
const keyInputControl = new MW.KeyInputControl();
// bind events
keyInputControl.addEventListener( 'movekeyon', () => playerController.isRunning = true );
keyInputControl.addEventListener( 'movekeyoff', () => playerController.isRunning = false );
keyInputControl.addEventListener( 'movekeychange', () => playerController.direction = keyInputControl.frontAngle );
keyInputControl.addEventListener( 'jumpkeypress', () => playerController.jump() );
( function update () {
const delta = clock.getDelta();
requestAnimationFrame( update );
world.step( Math.min( delta, 0.02 ) );
renderer.render( scene, camera );
} )();
</script>
</body>
</html>