我如何将我的子弹朝正确的方向定位?

时间:2014-12-25 19:17:08

标签: matrix rotation processing game-physics angle

我真的坚持这个。子弹的轨迹是完美的,但三角形应指向与玩家相同的方向。有什么方法可以让这成为可能。到目前为止,这是我的计划:

boolean up, right, down, left;
int x =-500;
int y =-500;
ArrayList<Bullet> bullets =  new ArrayList<Bullet>();
float a;

void setup()
{
  size(600, 600);
  smooth();
}

void draw()
{
  background(0);
  pushMatrix();
  translate(300, 300);
  a = atan2(mouseY-300, mouseX-300);
  rotate(a);
  fill(255);
  for (int i = x; i < x+800; i+=40)
    for (int j = y; j < y+800; j+=40)
      rect(i, j, 40, 40);
  for (Bullet b : bullets) b.update();
  popMatrix();
  fill(0, 0, 0);
  triangle(285, 300, 300, 250, 315, 300);
  if (up) 
  {
    x += sin(a)*5; 
    y += cos(a)*5;
  }
  if (left) 
  {
    y -= sin(a)*5; 
    x += cos(a)*5;
  }
  if (down) 
  {
    x -= sin(a)*5; 
    y -= cos(a)*5;
  }
  if (right) 
  {
    y += sin(a)*5; 
    x -= cos(a)*5;
  }
  if (mousePressed && frameCount % 8 == 0) bullets.add(new Bullet(a));
}

void keyPressed()
{
  if (key=='w')up=true;
  if (key=='a')left=true;
  if (key=='s')down=true;
  if (key=='d')right=true;
}

void keyReleased()
{
  if (key=='w')up=false;
  if (key=='a')left=false;
  if (key=='s')down=false;
  if (key=='d')right=false;
}

class Bullet
{
  float a;
  int y = 0;
  int x = 0;
  Bullet(float a)
  {
    this.a=a;
  }
  void update()
  {
    y-=cos(a)*6;
    x-=sin(a)*6;
    fill(255, 0, 0);
    triangle(x-3, y, x, y-10, x+3, y);
  }
}

1 个答案:

答案 0 :(得分:1)

如果你想获得2点之间的角度,你可以用以下方式使用atan2:

angle = atan2(playerY - bulletY, playerX - bulletX); //This angle is not returned in radians, to convert it simply use the function:
angle = degrees(angle);

当然之后你必须画出这样的三角形:

pushMatrix();
translate(centerOfTriangleX, centerOfTriangleY);
rotate(angle); //in radians, not in degrees
triangle(trX1 - centerOfTriangleX, trY1 - centerOfTriangleY...);
popMatrix();

要计算三角形的中心,对于多边形,已经有一个关于堆栈溢出的帖子:Finding the centroid of a polygon? 三角维基百科:http://en.wikipedia.org/wiki/Centroid#Of_triangle_and_tetrahedron

相关问题