02-02 - Move Player

02/02-02/02-02-js.html

                

01

Creat a const keys, then keyup and keydown

const keys = {
    up:{
        pressed: false
    },
    right:{
        pressed: false
    },
    down: {
        pressed: false
    }
    ,
    left:{
        pressed: false
    }
}
        
Place the lastKey variable to the last key up in the 'keyup' event listener. AND add e.preventDefault() in the 'keydown' event
addEventListener('keydown', e => {
let key = e.keyCode
switch (key){
    case 38:
        e.preventDefault()
        keys.up.pressed = true
        break
    case 39:
        e.preventDefault()
        keys.right.pressed = true
        break
    case 40:
        e.preventDefault()
        keys.down.pressed = true
        break
    case 37:
        e.preventDefault()
        keys.left.pressed = true
        break
}    
});
    
addEventListener('keyup', e => {
    let key = e.keyCode
    switch (key){
        case 38:
            keys.up.pressed = false
            lastKey = 'up'
            break
        case 39:
            keys.right.pressed = false
            lastKey = 'right'
            break
        case 40:
            keys.down.pressed = false
            lastKey = 'down'
            break
        case 37:
            keys.left.pressed = false
            lastKey = 'left'
            break
    }    
});

02

Create an update() method inside the Pacman class to add the velocity to the position

class Pacman {
constructor({ position, velocity }) {
    this.position = position
    this.velocity = velocity
    this.radius = 15
}
draw() {
    c.beginPath()
    c.fillStyle = 'yellow'
    c.arc(this.position.x, this.position.y, this.radius, 0, Math.PI * 2)
    c.fill()
    c.closePath()
}
update(){
    this.position.x += this.velocity.x
    this.position.y += this.velocity.y
    this.draw()
}
}
                

03

Adjust the velocity of the player inside of an animate() function like so

function animate(){
    requestAnimationFrame(animate)
    c.fillStyle = 'black'
    c.fillRect(0, 0, canvas.width, canvas.height)
    pacman.velocity.x = 0
    pacman.velocity.y = 0
    if (keys.up.pressed && lastKey != 'up') {
        pacman.velocity.y -= playerSpeed
    }else if(keys.right.pressed && lastKey != 'right'){
        pacman.velocity.x += playerSpeed
    } else if (keys.left.pressed && lastKey != 'left'){
        pacman.velocity.x -= playerSpeed
    }else if (keys.down.pressed && lastKey != 'down'){
        pacman.velocity.y += playerSpeed
    } 
    boundaries.forEach(el => {
        el.draw()
    })
    pacman.update()
}
animate()