'use strict'; // eslint-disable-line
/* global THREE, document, requestAnimationFrame */
function main() {
const canvas = document.querySelector('#c');
const renderer = new THREE.WebGLRenderer({canvas: canvas});
const fov = 60;
const aspect = 2; // the canvas default
const zNear = 0.1;
const zFar = 1000;
const camera = new THREE.PerspectiveCamera(fov, aspect, zNear, zFar);
camera.position.set(14, 8, 6);
camera.lookAt(-2, -2, 0);
const scene = new THREE.Scene();
{
const light = new THREE.DirectionalLight(0xffffff, 1);
light.position.set(0, 20, 0);
scene.add(light);
}
{
const light = new THREE.DirectionalLight(0xffffff, 1);
light.position.set(1, 2, 4);
scene.add(light);
}
const groundGeometry = new THREE.PlaneBufferGeometry(50, 50);
const groundMaterial = new THREE.MeshPhongMaterial({color: 0xCC8866});
const groundMesh = new THREE.Mesh(groundGeometry, groundMaterial);
groundMesh.rotation.x = Math.PI * -.5;
groundMesh.receiveShadow = true;
scene.add(groundMesh);
const zombieGeo = new THREE.ConeBufferGeometry(1, 1, 6);
zombieGeo.applyMatrix(new THREE.Matrix4().makeRotationX(Math.PI * 0.5));
const zombieMat = new THREE.MeshPhongMaterial({color: 'green', flatShading: true});
const zombieMeshes = [];
function makeZombie(x, z) {
const zombieMesh = new THREE.Mesh(zombieGeo, zombieMat);
scene.add(zombieMesh);
zombieMesh.position.set(x, 1, z);
zombieMeshes.push(zombieMesh);
}
for (let v = -5; v <= 5; v += 5) {
makeZombie(v, -10);
makeZombie(v, 10);
makeZombie(-5, v);
makeZombie( 5, v);
}
const playerGeo = new THREE.SphereBufferGeometry(1, 6, 4);
const playerMat = new THREE.MeshPhongMaterial({color: 'red', flatShading: true});
const playerMesh = new THREE.Mesh(playerGeo, playerMat);
scene.add(playerMesh);
function resizeRendererToDisplaySize(renderer) {
const canvas = renderer.domElement;
const width = canvas.clientWidth;
const height = canvas.clientHeight;
const needResize = canvas.width !== width || canvas.height !== height;
if (needResize) {
renderer.setSize(width, height, false);
}
return needResize;
}
function render(time) {
time *= 0.001;
if (resizeRendererToDisplaySize(renderer)) {
const canvas = renderer.domElement;
camera.aspect = canvas.clientWidth / canvas.clientHeight;
camera.updateProjectionMatrix();
}
playerMesh.position.set(Math.sin(time) * 6, 1, Math.cos(time) * 6);
for (const zombieMesh of zombieMeshes) {
zombieMesh.lookAt(playerMesh.position);
}
renderer.render(scene, camera);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
}
main();
body { margin: 0; }
canvas { width: 100vw; height: 100vh; display: block; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/99/three.min.js"></script>
<canvas id="c"></canvas>