D
D
durnevdanya2017-06-25 14:32:01
JavaScript
durnevdanya, 2017-06-25 14:32:01

How to update the position of images on Canvas?

Hello. Wrote a function to assign image positions on the canvas.
app.js (game)

my_Doge = game.addSprite("Doge", "mydoggy", 0, 700, 100, 100);

When an object is added, it is written to the array this.addedSprites
Library.js
this.addedSprites.push(spriteObj);
I also wrote a way to change the position for it
game.setPos(my_Doge, my_Doge.xcoord+=2, my_Doge.ycoord);

After changing the position in the library, the render method occurs
GameWindow.prototype.setPos = function(sprite, newX, newY)
{ // Set new sprite position
  sprite.xcoord = newX;
  sprite.ycoord = newY;

  for(var i = 0; i < this.addedSprites.length; i++)
  {
    if(sprite.id == this.addedSprites[i].id)
    {
      this.addedSprites[i].xcoord = newX;
      this.addedSprites[i].ycoord = newY;
    }
  }

  this.render(sprite, sprite.width, sprite.height, sprite.xcoord, sprite.ycoord);
}

GameWindow.prototype.render = function(sprite, width, height, x, y)
{
  ctx = this.ctx;

    canvas.width=canvas.width;

    ctx.drawImage(sprite, x, y, width, height);

}

Here's what happens:
ezgif_com-video-to-gif.gif?extra=boes9cG
If you remove the method
game.setPos(my_Doge, my_Doge.xcoord+=2, my_Doge.ycoord);
(so that the dog does not move), you can see. that I added a cat before, but it disappears, and only the dog is updated.
x8IPRw7d0UQ.jpg
Okay, I tried the following thing - so that all objects from the array of added objects are this.addedSpritesalso drawn to the canvas by looping
gameWindow.prototype.render = function(sprite, width, height, x, y)
{
  ctx = this.ctx;

    canvas.width=canvas.width;

    for(var i = 0; i < this.addedSprites.length; i++)
    {
    	var w = new Image();
    	w.src = this.addedSprites[i].src;
    	ctx.drawImage(w, this.addedSprites[i].x,this.addedSprites[i].y,this.addedSprites[i].width,this.addedSprites[i].height);
    }

    ctx.drawImage(sprite, x, y, width, height);

}

but it didn't work out very well:
ezgif_com-video-to-gif_1.gif?extra=8LLe3
What's the problem? I do not understand how to make only other objects appear, and not the main character, who is already moving? Maybe the problem is in the render method?
Thank you very much
P.S
If you register movement for two objects, and not just for one
game.setPos(my_Doge, my_Doge.xcoord+=2, my_Doge.ycoord);
  game.setPos(my_Cat, my_Cat.xcoord+=2, my_Cat.ycoord);

Then only the one that is registered last will move

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question