Canvas animation Player

move with keys

by DupontTD

CSS

canvas {
  border: 1px solid #d3d3d3;
  background-color: #f1f1f1;
}

JavaScript

class Player {

  constructor({
    keysMap,
    x,
    y,
    speed,
    width,
    height,
    color,
    type
  }) {

    Object.assign(this, {
      keysMap,
      x,
      y,
      speed,
      width,
      height,
      color,
      type
    });

    this.angle = 0;
    this.moveAngle = 0;
    
    this.keys = [];


  }

  static create({
    keysMap = new Map([
      ["ArrowUp", "up"],
      ["ArrowRight", "right"],
      ["ArrowDown", "down"],
      ["ArrowLeft", "left"],
    ]),
    x = myGameArea.canvas.width/2,
    y = myGameArea.canvas.height/2,
    speed = 0,
    color = "red",
    type = "car",
    width = 5,
    height = 20,

  } = {}) {
    console.log(myGameArea);
    return new Player({
      keysMap,
      x,
      y,
      speed,
      width,
      height,
      color,
      type
    })

  }


  handleInput(e) {

   let keyPressed = e.key;
   
   
    //console.log(type);
    //console.log("handleinput key = " + keyPressed);

    // don't move with bad key touch
    if (!this.keysMap.has(keyPressed)) {
      console.log(" pas la clef" + this.keysMap.has(keyPressed))
      return;
    }
    
     this.keys = (this.keys || []);
    

    // use virtual key (up,down ...)
    let key = this.keysMap.get(keyPressed);


    // don't let player go off zonescreen.
    if (key === 'right') {
         this.keys[key] = (e.type == "keydown");
  
    }
    if (key === 'left') {
         this.keys[key] = (e.type == "keydown");
 
    }

    if (key === 'up') {
     this.keys[key] = (e.type == "keydown");
   
    }

    if (key === 'down') {
     
        this.keys[key] = (e.type == "keydown");
    }

    


  }

  render() {
  
    //myGameArea.clear(); not place here
    this.moveAngle = 0;
    this.speed = 0

    let ctx = myGameArea.context;
    ctx.save();
    ctx.translate(this.x, this.y);
    ctx.rotate(this.angle);
    ctx.fillStyle = this.color;
    ctx.fillRect(this.width / -2, this.height / -2, this.width, this.height); 
    ctx.restore();
   
  }
 ...