Reputation: 29
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)
}
Upvotes: 1
Views: 917
Reputation: 101
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);
}
Upvotes: 1