Sorce Code


Sorce Code

HTML

<html>

<html lang="en">

<head>

  <meta charset="UTF-8" />

  <title>3D World Game</title>

  <style>

    body { margin: 0; overflow: hidden; }

    canvas { display: block; }

  </style>

</head>

<body>

 

  <script src="script.js"></script>

</body>

</html>

JS

// Scene setup

const scene = new THREE.Scene();

const camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);

const renderer = new THREE.WebGLRenderer();

renderer.setSize(window.innerWidth, window.innerHeight);

document.body.appendChild(renderer.domElement);

// Light

const light = new THREE.DirectionalLight(0xffffff, 1);

light.position.set(5, 10, 7.5);

scene.add(light);

// World Generation (Flat terrain of cubes)

const worldSize = 20;

const cubeSize = 1;

const geometry = new THREE.BoxGeometry(cubeSize, cubeSize, cubeSize);

const material = new THREE.MeshLambertMaterial({ color: 0x4caf50 });

for (let x = -worldSize; x < worldSize; x++) {

  for (let z = -worldSize; z < worldSize; z++) {

    const cube = new THREE.Mesh(geometry, material);

    cube.position.set(x * cubeSize, -0.5, z * cubeSize);

    scene.add(cube);

  }

}

// Player setup

camera.position.set(0, 2, 5);

// Movement controls

const keys = {};

document.addEventListener('keydown', e => keys[e.key.toLowerCase()] = true);

document.addEventListener('keyup', e => keys[e.key.toLowerCase()] = false);

const clock = new THREE.Clock();

function animate() {

  requestAnimationFrame(animate);

  const delta = clock.getDelta();

  const speed = 5;

  if (keys['w']) camera.position.z -= speed * delta;

  if (keys['s']) camera.position.z += speed * delta;

  if (keys['a']) camera.position.x -= speed * delta;

  if (keys['d']) camera.position.x += speed * delta;

  renderer.render(scene, camera);

}

animate();

Files

Download 6 kB
81 days ago

Get OFFLINE [TESTING]

Leave a comment

Log in with itch.io to leave a comment.