试图让一个三角形指向鼠标

Trying to get a triangle to point to the mouse

我不想承认这一点,但我对一款刚刚开始流血的游戏非常着迷。

这个概念真的很简单,我有一个三角形,我想指向鼠标的位置。自然地,我在 p5.js 中使用 atan2 函数,因为推荐用于此类任务。我知道我计算的旋转量是错误的,我希望它通过三角形的中点旋转,但将尖端指向鼠标。如果有人能带我了解这背后的数学原理,我将不胜感激。

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

你的计算是正确的!

您可能遗漏了一个与渲染相关的小细节:0 radians/degrees 指向右侧,您的假设可能是绘制三角形时 0 度指向上方。

我会保持计算不变,以防万一您需要在以后的开发中将此角度用于其他游戏对象。相反,我只是将旋转偏移 90 度 (HALF_PI) 以进行渲染,以说明三角形是向上绘制而不是向右倾斜 0 度的事实:

rotate(this.radians + HALF_PI);

当然,您可以更新 triangle 调用以绘制指向右侧的三角形。

玩得开心!