Spaces:
Running
Running
<html> | |
<head> | |
<meta charset="utf-8"> | |
<title>Tilemap Example</title> | |
<style> | |
body { | |
margin: 0; | |
overflow: hidden; | |
} | |
canvas { | |
width: 100%; | |
height: 100%; | |
} | |
</style> | |
</head> | |
<body> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script> | |
<script> | |
// create the scene | |
var scene = new THREE.Scene(); | |
// create the camera | |
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); | |
camera.position.z = 5; | |
// create the renderer | |
var renderer = new THREE.WebGLRenderer(); | |
renderer.setSize(window.innerWidth, window.innerHeight); | |
document.body.appendChild(renderer.domElement); | |
// create the tilemap | |
var tilemap = [ | |
[0, 0, 0, 0, 0], | |
[0, 1, 1, 1, 0], | |
[0, 1, 1, 1, 0], | |
[0, 1, 1, 1, 0], | |
[0, 0, 0, 0, 0], | |
]; | |
var tileSize = 1; | |
var tileGeometry = new THREE.PlaneGeometry(tileSize, tileSize); | |
var tileMaterial = new THREE.MeshBasicMaterial({ color: 0xffffff }); | |
var tiles = []; | |
for (var i = 0; i < tilemap.length; i++) { | |
for (var j = 0; j < tilemap[i].length; j++) { | |
if (tilemap[i][j] === 1) { | |
var tile = new THREE.Mesh(tileGeometry, tileMaterial); | |
tile.position.x = (j - tilemap[i].length / 2) * tileSize; | |
tile.position.y = (-i + tilemap.length / 2) * tileSize; | |
scene.add(tile); | |
tiles.push(tile); | |
} | |
} | |
} | |
// create the arrow buttons | |
var arrowUp = document.createElement('button'); | |
arrowUp.innerText = 'β'; | |
arrowUp.style.position = 'absolute'; | |
arrowUp.style.left = '50%'; | |
arrowUp.style.top = '10px'; | |
arrowUp.addEventListener('click', function() { | |
camera.position.y += 1; | |
}); | |
document.body.appendChild(arrowUp); | |
var arrowDown = document.createElement('button'); | |
arrowDown.innerText = 'β'; | |
arrowDown.style.position = 'absolute'; | |
arrowDown.style.left = '50%'; | |
arrowDown.style.bottom = '10px'; | |
arrowDown.addEventListener('click', function() { | |
camera.position.y -= 1; | |
}); | |
document.body.appendChild(arrowDown); | |
var arrowLeft = document.createElement('button'); | |
arrowLeft.innerText = 'β'; | |
arrowLeft.style.position = 'absolute'; | |
arrowLeft.style.left = '10px'; | |
arrowLeft.style.top = '50%'; | |
arrowLeft.addEventListener('click', function() { | |
camera.position.x -= 1; | |
}); | |
document.body.appendChild(arrowLeft); | |
var arrowRight = document.createElement('button'); | |
arrowRight.innerText = 'β'; | |
arrowRight.style.position = 'absolute'; | |
arrowRight.style.right = '10px'; | |
arrowRight.style.top = '50%'; | |
arrowRight.addEventListener('click(function() { | |
camera.position.x += 1; | |
}); | |
document.body.appendChild(arrowRight); | |
// animate the scene | |
function animate() { | |
requestAnimationFrame(animate); | |
renderer.render(scene, camera); | |
} | |
animate(); | |
</script> | |
</body> | |
</html> |