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

时间:2021-01-17 00:41:54

标签: javascript math trigonometry p5.js vector-graphics

我试图制作一个程序,尽管它偏离原点,但仍将精灵指向我的鼠标。

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

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

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)
}

1 个答案:

答案 0 :(得分:0)

所以现在你的角色像我想的那样移动(无论鼠标位置如何 - 向前方向始终是屏幕顶部):

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);
}