10

标题说明了一切,我试图根据它所处的角度向前移动一个对象。

这是我的相关代码:

xView =  this.x-this.width/2;
yView =  this.y-this.height/2; 
playerCtx.drawImage(imgSprite, 0, 0, this.width, this.height, xView, yView, this.width, this.height); 
      playerCtx.save();     
      playerCtx.clearRect(0, 0, game.width, game.height);
      playerCtx.translate(xView, yView);
      playerCtx.rotate(angle *Math.PI/180);
      playerCtx.drawImage(imgSprite, 0, 0, this.width, this.height, -xView, -yView, this.width, this.height); 
      playerCtx.restore();
    }
        if(Game.controls.left) {
    angle-=1; 
        if(Game.controls.up){
        this.x +=   this.speed * Math.cos(angle * Math.PI / 180);
        this.y -=   this.speed * Math.sin(angle * Math.PI / 180);
        }

对象不移动对应于var angle

编辑

我不知道为什么我的代码不起作用,所以我使用了一个包含 36 个不同角度的精灵表。这行得通,但是旋转太快了。如果有人能告诉我为什么以上不能正常工作,或者我将如何使以下功能变慢:

if(Game.controls.right) {
    currentFrame++;
    angle+=10;
 }

较慢的意思是当按住左键时,angle+10; currentFrame++;正在提高到快速,并且添加更多帧可能需要太长时间。

编辑

为我的原始问题添加了一个Jfiddle,角度变量随着旋转而移动,例如,如果对象面向右侧,角度将等于 90,但对象看起来仍然不像向右移动,尽管相机确实如此.

4

1 回答 1

15

尝试改变 cos 和 sin 以及符号:

this.x += this.speed * Math.cos(angle * Math.PI / 180);
this.y += this.speed * Math.sin(angle * Math.PI / 180);

要进行旋转(在问题的已编辑部分),您需要基本上减少步骤并提供更多精灵。更多的精灵不会变慢,但会使用更多的内存并增加初始加载时间。

更新

好的,您需要更正一些事情(上面是其中之一,它们在小提琴中得到了更正)。

修改过的小提琴

其他内容在:

在你的update()方法中:

// Add both here as angle with correctly use neg/pos
if (Game.controls.up) {
    this.x += this.speed * Math.cos(angle * Math.PI / 180);
    this.y += this.speed * Math.sin(angle * Math.PI / 180);
}

/// Sub both here as angle with correctly use neg/pos
if (Game.controls.down) {
    this.x -= this.speed * Math.cos(angle * Math.PI / 180);
    this.y -= this.speed * Math.sin(angle * Math.PI / 180);
}

由于角度将确定负值或正值,您只需根据意图添加或减去,因此向上添加两个值,向下减去两个值。角度将确保增量正确签名。

在你的draw函数中有几件事:

Player.prototype.draw = function (context, xView, yView) {

    // Add the half width instead of subtract it
    xView = this.x + this.width / 2;
    yView = this.y + this.height / 2;

    // not needed as you clear the canvas in the next step
    //playerCtx.drawImage(imgSprite, 0, 0, ....
    playerCtx.save();
    playerCtx.clearRect(0, 0, game.width, game.height);

    // make sure pivot is moved to center before rotation
    playerCtx.translate(xView, yView);

    // rotate, you should make new sprite where direction
    // points to the right. I'm add 90 here to compensate
    playerCtx.rotate((angle + 90) * Math.PI / 180);

    // translate back before drawing the sprite as we draw
    // from the corner and not the center of the image
    playerCtx.translate(-xView, -yView);

    playerCtx.drawImage(imgSprite, 0, 0, this.width, this.height, this.x, this.y, this.width, this.height);

    playerCtx.restore();
}

现在你会看到一切正常。

你的图像应该总是指向右边。这是因为那始终是 0 度角。这将为您省去一些麻烦。我通过将角度添加 90 度来补偿这是绘制功能,但这应该在精灵本身中进行调整。

此外,我修改了您的密钥处理程序(有关详细信息,请参阅演示)。

于 2013-10-14T07:08:33.837 回答