如何在P5中使移动精灵指向鼠标?



我试图编写一个程序,使一个精灵指向我的鼠标,尽管它偏离了原点。

当它在原点时旋转得很好,但很明显,当我开始移动精灵时,它会基于原点旋转,而不是基于它的位置。

如何使我的旋转与精灵的位置正确相关?下面是我的代码:

var x = 0;
var y = 0;
function setup() {
createCanvas(600, 600);
rectMode(CENTER)
}
function draw() {

background(0);
let posX = width/2;
let posY = height/2;

if (keyIsDown(87)) {y = y - 1;}
if (keyIsDown(83)) {y = y + 1;}
if (keyIsDown(65)) {x = x - 1;}
if (keyIsDown(68)) {x = x + 1;}

let angle = Math.atan2(mouseY-posY, mouseX-posX);
translate(posX, posY);
rotate(angle)
square(x,y,100)
}

所以现在你的角色移动就像我认为你想要的(不管鼠标位置-前进方向总是屏幕的顶部):

var x = 0;
var y = 0;
function setup() {
createCanvas(600, 600);
rectMode(CENTER)
}
function draw() {
background(0);
let posX = width/2;
let posY = height/2;
//I went back to the moving way of your character which was before, and i hope this is what you expect:
let angle = Math.atan2(mouseY - posY - y, mouseX - posX - x);
if (keyIsDown(87)) {y = y - 1;}
if (keyIsDown(83)) {y = y + 1;}
if (keyIsDown(65)) {x = x - 1;}
if (keyIsDown(68)) {x = x + 1;}
//And here is the same as was before:
translate(posX + x, posY + y);
rotate(angle);
square(0,0,100);
}

最新更新