Skip to content

Instantly share code, notes, and snippets.

@anotheredward
Created August 9, 2016 23:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anotheredward/edc6322db3459cff9c37524c4f54add3 to your computer and use it in GitHub Desktop.
Save anotheredward/edc6322db3459cff9c37524c4f54add3 to your computer and use it in GitHub Desktop.
First-person Walker
<canvas id='canvas' width='1000' height='1000'>
<script>
const c = document.getElementById('canvas')
const ctx = c.getContext('2d')
const unit = 100
let player = {x: 1, y: 1}
let wall = {x: 1, y:0 }
//wall position is 1,0, wall is unit size
//wall width and height decrease linerarly with distance
//player 1,2
//canvas is 1000x1000, a wall 1 block away is 100x100
ctx.fillStyle = 'green'
function render() {
ctx.clearRect(0,0,1000,1000)
let distance = (player.y - wall.y)
let offset = (player.x - wall.x)
ctx.fillRect(unit * -offset, unit, unit * distance , unit * distance)
}
const keyCodeToDirection = {
37: {x: -0.1, y: 0},
38: {x: 0, y: 0.1},
39: {x: 0.1, y: 0},
40: {x: 0, y: -0.1}
}
document.onkeydown = function (e) {
const direction = keyCodeToDirection[e.keyCode]
if (direction) {
e.preventDefault()
player.y += direction.y
player.x += direction.x
render()
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment