T
T
Triborg-3332019-08-27 19:28:40
JavaScript
Triborg-333, 2019-08-27 19:28:40

Why does Animation go to the usual variable, for example, position.x++, but not to this.position.x++?

Help me please. Animation goes to the usual variable.

let canvas, ctx, width, height;

let Game = function(){

  canvas = document.getElementById('knight');
  ctx = canvas.getContext('2d');

  canvas = width = window.innerWidth;
  canvas = height = window.innerHeight;

  var gameSize = {

  }

  this.loadGame();
}

const bg = new Image();
bg.src = "img/bg.png";

Game.prototype.startGame = function(){
  this.loadGame();
}


Game.prototype.loadGame = function(){
  this.knight();
  this.update();
  this.draw();

  requestAnimationFrame(()=>{
 		this.loadGame();
  });
}


Game.prototype.knight = function(game, gameSize,position){
  this.game = game;
  this.position = {x : 150, y : 150};
  this.size = {x : 200, y : 230};
  this.current = 0;
  this.knight = [];
}

Game.prototype.update = function(){
  
}


Game.prototype.draw = function(){
  ctx.drawImage(bg, 0, 0);
  ctx.fillRect(this.position.x++, this.position.y, 150, 150)
}


window.onload = function(){
  new Game("ctx");
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
RAX7, 2019-08-27
@Triborg-333

First, the knight method in the prototype is overridden by the knight property

Game.prototype.knight = function(game, gameSize,position){
  this.game = game;
  this.position = {x : 150, y : 150};
  this.size = {x : 200, y : 230};
  this.current = 0;
  this.knight = []; // <----- упс! следующий вызов this.knight() окажется неудачным.
}

Second, raf calls loadGame recursively, loadGame calls knight, knight overwrites the this.position object, so neither x nor y is changed.
Third, code in a sandbox so that others don't have to do it for you.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question