HTML Canvas将角色的枪旋转到面向鼠标
问题描述:
我对Javascript很陌生,我开始了一个简单的游戏。我希望角色的枪旋转跟随鼠标。到目前为止,移动和其他一切工作正常,除了当我添加旋转功能时,角色似乎围绕着屏幕旋转了一个巨大的圆圈。这里的的jsfiddle:https://jsfiddle.net/jvwr8bug/#HTML Canvas将角色的枪旋转到面向鼠标
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的修复。
答
你正在旋转当前变换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);