我已经查看了多个线程,并且在我的一生中都无法使图像正确旋转到鼠标光标的位置。我可以将图像转换为鼠标光标的位置,我知道我已经靠近了,我只是不知道确切的位置……下面是我到目前为止的情况。图片需要在当前位置旋转,如果更有意义,请面对鼠标光标... PS我是编码新手!
var myGamePiece;
function startGame() {
myGamePiece = new component(50, 50, "Assets/PNG/Soldier 1/soldier1_gun.png", 10, 120, "image"); //size, source, starting location
myGameArea.start();
}
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.frameNo = 0;
this.interval = setInterval(updateGameArea, 1);
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
stop : function() {
clearInterval(this.interval);
}
}
function component(width, height, color, x, y, type) {
this.type = type;
if (type == "image") {
this.image = new Image();
this.image.src = color;
}
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function() {
this.width = window.innerWidth/20; //update width based on window size
this.height = window.innerHeight/20; //update height based on window size
ctx = myGameArea.context;
if (type == "image") {
document.onmousemove = function(e) {
dx = e.pageX;
dy = e.pageY;
console.log(e.pageX, e.pageY);
theta = Math.atan2(dy - this.y, dx - this.x);
theta = theta * (180/Math.PI);
}
//console.log(theta);
ctx.save();
ctx.translate(this.image.width/2,this.image.height/2); // updates the image origin upon rotating
ctx.rotate(theta); // rotates the image to specified position
ctx.drawImage(this.image,
this.x,
this.y,
this.width, this.height);
ctx.restore();
} else {
console.log("failed");
}
}
this.newPos = function() {
this.x += this.speedX;
this.y += this.speedY;
}
}
function updateGameArea() {
myGameArea.clear();
myGamePiece.newPos();
myGamePiece.update();
}
function moveup() {
myGamePiece.speedY = -1;
}
function movedown() {
myGamePiece.speedY = 1;
}
function moveleft() {
myGamePiece.speedX = -1;
}
function moveright() {
myGamePiece.speedX = 1;
}
function clearmove() {
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
}
var keys;
setInterval(mainLoop, 50);
function mainLoop(){
document.addEventListener("keydown", function (e) {
keys = (keys || []);
keys[e.keyCode]=true;
if (keys[37]){ // left
moveleft();
}
if (keys[38]){ // up
moveup();
}
if (keys[39]){ // right
moveright();
}
if (keys[40]){ // down
movedown();
}
} , false);
document.addEventListener("keyup", function (e) {
keys[e.keyCode]=false;
stop();
clearmove();
if (keys[37]){ // left
moveleft();
}
if (keys[38]){ // up
moveup();
}
if (keys[39]){ // right
moveright();
}
if (keys[40]){ // down
movedown();
}
}, false);
}