HTML5画布和javascript移动鼠标移动播放器

时间:2015-04-24 16:19:14

标签: javascript html5 function canvas html5-canvas

好吧到目前为止我可以用箭头键移动玩家但是我一直在试图弄清楚如何用鼠标移动移动玩家,例如向右移动鼠标会增加玩家X的位置并将鼠标移动到左边会减少X的位置但是我很难实现这个目标!

我如何制作我的玩家对象

UPDATE `user` 
SET user_password = CONCAT(':B:somesalt:', MD5(CONCAT('somesalt-', MD5('somepass')))) 
WHERE user_name = 'someuser';

我的控制功能

player = {
    x: width / 30,//player properties 
    y: height - 5,
    width: 16,
    height: 18,
    speed: 3,
    velX: 0,
    velY: 0,
    jumping: false,
    grounded: false

},

我如何获得钥匙

 if (keys[38] || keys[32]) {
    // up arrow or space
    if (!player.jumping && player.grounded) {
        player.jumping = true;
        player.grounded = false;
        player.velY = -player.speed * 2;
        var audio = new Audio('jump.mp3');
        audio.play();
    }
}
if (keys[39]) {
//mouseControl = false;
    // right arrow
    if (player.velX < player.speed) {
        player.velX++;

if(count ==2)
 {
 count = 0;
 }
else {
 count++;
}
    }
}
     if (keys[37]) {
   //mouseControl = false;
    // left arrow
    if (player.velX > -player.speed) {
        player.velX--;
        if(count ==2)
  {
   count = 0;

}
 else {
 count++;
 }
    }
}

player.velX *= friction;
player.velY += gravity;

ctx.clearRect(0, 0, width, height);
ctx.fillStyle = "black";
ctx.beginPath();

player.grounded = false;
}

1 个答案:

答案 0 :(得分:0)

您要做的是添加mousemove事件。并且有两个变量来存储oldXoldY鼠标位置,以及newXnewY鼠标位置。然后,在每次拨打mousemove时,newXnewY将是当前鼠标位置,而oldXoldY将是最后一次呼叫的鼠标位置mousemove。最后,您只需减去newX - oldX即可获得您的鼠标X位置(diffX)的差异。如果它是正数,则将鼠标移动到右侧,如果它是负数,则将鼠标移动到左侧。 diffY也是如此。这是一个例子:

var oldX = 0, oldY = 0, newX, newY;

canvas.addEventListener("mousemove", function(e) 
{ 
    // Get the current mouse position
    var cRect = canvas.getBoundingClientRect();
    newX = e.clientX - cRect.left;
    newY = e.clientY - cRect.top;

    // Subtract from the old mouse position
    var diffX = newX - oldX;     
    var diffY = newY - oldY;         

    ctx.clearRect(0,0,canvas.width,canvas.height);

    if(diffX > 0)
        player.x += player.speed; // If the mouse moved right, move right
    else
        player.x -= player.speed; // Otherwise move left.

    ctx.fillRect(player.x, player.y, 50, 50); // draw player

    // Now make the current mouse potion the old mouse position
    oldX = newX;
    oldY = newY
});

Here is a working fiddle example