【问题标题】:Spritesheet not animating HTML5 CanvasSpritesheet 没有为 HTML5 Canvas 设置动画
【发布时间】:2020-09-09 19:15:00
【问题描述】:

一段时间以来,我一直在尝试让我的播放器制作动画,并且我已经阅读了多个教程,但我似乎无法做到这一点。我正在关注的教程位于:https://www.simplifiedcoding.net/javascript-sprite-animation-tutorial-html5-canvas/

我创建了一个组件类的播放器:

 mySprite = new component(168, 33, "Images/Run/character.png", 0, 0, "sprite");

然后我用更新函数创建组件类:

function component(width, height, color, x, y,type) 
{
  this.width = width;
  this.height = height;
  this.type = type;
  if (type == "image" || type == "background" || type == "sprite" ) {
    this.image = new Image();
    this.image.src = color;
  }
  this.x = x;
  this.y = y;


  this.update = function()
  {
  ctx = myGameArea.context;
  if (this.type == "sprite") 
    { 
     var curFrame = 0;
     curFrame = ++curFrame % 8; 
     var srcX =0;       
     srcX = curFrame * this.width /8; 
     ctx.drawImage(this.image,srcX,y,this.width/8,this.height,x,y,this.width/8,this.height);
    } 

  }
  this.newPos = function() 
  {
    this.gravitySpeed += this.gravity;
    this.x += this.speedX;
    this.y += this.speedY + this.gravitySpeed;
    this.hitBottom();
    this.jumpGravity();
    if (this.type == "background") {
      if (this.x == -(this.width)) {
        this.x = 0;
      }
    } 
}
}

然后我在游戏循环中同时调用 update 和 newPos 函数:

mySprite.newPos();
  mySprite.update();

我希望有人能告诉我我做错了什么。

【问题讨论】:

    标签: html animation canvas html5-canvas sprite-sheet


    【解决方案1】:

    我在调试 curFrame 变量时注意到它没有递增。我通过使 curframe 成为组件类的变量并在游戏循环中直接使用 this.curFrame +=1; 递增它来解决这个问题。

    【讨论】:

      猜你喜欢
      • 2016-08-07
      • 1970-01-01
      • 2013-03-24
      • 2011-12-25
      • 2018-12-29
      • 2015-06-09
      • 2015-08-13
      • 1970-01-01
      • 2011-04-27
      相关资源
      最近更新 更多