【问题标题】:How to Make Moving Sprite Point Toward Mouse in P5?如何在 P5 中使移动精灵指向鼠标?
【发布时间】:2021-01-17 00:41:54
【问题描述】:

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

它在原点处旋转很好,但显然,当我开始将精灵移开时,它认为是根据原点而不是位置旋转。

我怎样才能使我的旋转与我的精灵位置正确相关?这是我的代码:

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

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 这太棒了!它实际上并不是我想要的,而是我以后肯定会使用的另一个很棒的运动系统。在我正在寻找的移动中,我希望角色即使左右移动也总是看向鼠标。在这种情况下,角色看起来像是在看鼠标,但移动发生了变化,因此向前的方向是鼠标矢量。
    • 我知道,但我认为这就是您想要的。例如,您的意思是通过按“w”键,您的角色会沿着屏幕向上走,而不是走向鼠标?
    • 换句话说,你希望你的角色总是朝着同一个方向移动,而不管鼠标的位置如何?
    猜你喜欢
    • 1970-01-01
    • 2012-11-29
    • 1970-01-01
    • 1970-01-01
    • 2011-01-26
    • 1970-01-01
    • 2020-02-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多