HTML Canvas旋转角色的枪以面向鼠标

时间:2016-11-19 03:23:41

标签: html canvas

我对Javascript很新,我开始了一个简单的游戏。我希望角色的枪旋转以跟随鼠标。到目前为止,运动和其他一切工作正常,除了当我添加旋转功能时,角色似乎在屏幕周围旋转一个巨大的圆圈。这是jsfiddle:https://jsfiddle.net/jvwr8bug/#

function getMousePos(canvas, evt) {
  var rect = canvas.getBoundingClientRect();
  var mouseX = evt.clientX - rect.top;
  var mouseY = evt.clientY - rect.left;
  return {
    x: mouseX,
    y: mouseY
  };
}

window.addEventListener('load', function() {
  canvas.addEventListener('mousemove', function(evt) {
    var m = getMousePos(canvas, evt);
    mouse.x = m.x;
    mouse.y = m.y;
  }, false);
}, false);

错误似乎在某处,但显然它可能是其他东西

**编辑:感谢Blindman67的修复。

1 个答案:

答案 0 :(得分:0)

您正在每帧rotation旋转当前变换。 ctx.rotate(a)旋转当前变换,因此每次调用时,您都会将旋转量增加a。将其视为相对旋转而不是设置绝对旋转。

要修复代码,请使用

替换佳能渲染
  //cannon
  //ctx.rotate(rotation);  // << you had

  // setTransform overwrites the current transform with a new one
  // The arguments represent the vectors for the X and Y axis
  // And are simply the direction and length of one pixel for each axis
  // And a coordinate for the origin.
  // All values are in screen/canvas pixels coordinates
  // setTransform(xAxisX, xAxisY, yAxisX, yAxisY, originX, originY)
  ctx.setTransform(1,0,0,1,x,y); // set center of rotation (origin) to center of gun
  ctx.rotate(rotation); // rotate about that point.
  ctx.fillStyle = "#989898";
  ctx.fillRect(15, - 12.5, 25, 25);  // draw relative to origin
  ctx.lineWidth = 2;
  ctx.strokeStyle = "#4f4f4f";
  ctx.strokeRect( 15,- 12.5, 25, 25); // draw relative to origin
  //body
  ctx.fillStyle = "#5079c4";
  ctx.beginPath();
  ctx.arc(0, 0, size, 0, Math.PI * 2); // draw relative to origin
  ctx.fill();
  ctx.stroke();

  // can't leave the transformed state as is because that will effect anything else
 // that will be rendered. So reset to the default.
  ctx.setTransform(1,0,0,1,0,0);   // restore the origin to the default 

还有一些问题可以让它发挥作用

正好在渲染之上,正典获得了鼠标的方向

// you had coordinates mixed up
// rotation = Math.atan2(mouse.x - y, mouse.y - x); // you had (similar)

rotation = Math.atan2(mouse.y - y, mouse.x - x);

你的鼠标事件监听器正在混合坐标而不是非常有效地运行

替换所有鼠标代码。你不需要onload,因为画布已经存在。

canvas.addEventListener('mousemove', function(evt) {
    var rect = this.getBoundingClientRect();
    mouse.x = evt.clientX - rect.left; // you had evt.clientX - rect.top
    mouse.y = evt.clientY - rect.top;  // you had evt.clientY - rect.left
}, false);