I hate to admit it, but I am awfully stuck on a game I have only just bleeding started.
The concept is quite simple really, I have a triangle that I want to point to the mouses position. Naturally I use the atan2 function in p5.js as this is recommended for such tasks. I know I am calculating the amount to rotate wrong, I want it to rotate via the midpoint of the triangle but point the tip towards the mouse. If somebody could walk me through the maths behind this I would greatly appreciate it.
var player;
function setup() {
createCanvas(400, 400);
player = new Player();
}
function draw() {
background(0)
fill(255);
player.update();
}
function Player() {
this.pos = createVector(width/2, height/2);
this.r = 20;
this.direction = 0;
this.radians = 0;
this.update = function() {
push();
stroke(255);
noFill();
translate(this.pos.x, this.pos.y);
this.radians = atan2(mouseY-this.pos.y, mouseX-this.pos.x);
rotate(this.radians);
triangle(-this.r, this.r, this.r, this.r, 0, -this.r);
ellipse(0, 0, 20, 20);
pop();
}
}
Your calculation is correct!
You might be missing one minor detail related to rendering: 0 radians/degrees points to the right and your assumption might be that 0 degrees points up as you draw your triangle.
I'd keep the calculation as is just in case you need to use this angle for other game objects in later development. Instead, I'd simply offset the rotation by 90 degrees (HALF_PI
) for rendering to account for the fact that triangle is drawn tip up and not tip right for 0 degrees:
rotate(this.radians + HALF_PI);
Alternatively off course, you can update the triangle
call to draw the triangle pointing to the right.
Have fun!
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加