I'm really stuck on this. The trajectory of the bullets are perfect but the triangle should point in the same direction as the player. Is there any way i can make this possible. Here is my program so far:
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);
}
}
If you want to get an angle between 2 points you can use atan2 the following way:
angle = atan2(playerY - bulletY, playerX - bulletX); //This angle is not returned in radians, to convert it simply use the function:
angle = degrees(angle);
Of course afterwards you have to draw the triangle like this:
pushMatrix();
translate(centerOfTriangleX, centerOfTriangleY);
rotate(angle); //in radians, not in degrees
triangle(trX1 - centerOfTriangleX, trY1 - centerOfTriangleY...);
popMatrix();
To calculate the centre of the triangle, there is a post on stack overflow already for polygons: Finding the centroid of a polygon? Wikipedia for Triangle: http://en.wikipedia.org/wiki/Centroid#Of_triangle_and_tetrahedron