简体   繁体   中英

How to Make Moving Sprite Point Toward Mouse in P5?

I was trying to make a program that pointed a sprite toward my mouse despite its displacement from the origin.

It rotates fine when it is at the origin, but obviously, when I start to move the sprite away, it thinks to rotate based on the origin and not it's position.

How can I make my rotation related to my sprites position properly? Here is my code:

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

So now your character moves like I think you want to (regardless of the mouse position - the forward direction is always the top of screen):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM