Flying Triangles with Java

I recently began a project to create a graphical animation in which a triangle traveled across a static sky. It was a lot of fun to create, and it is a great way to teach myself more about graphical animation techniques and Java.

To get started, I first created a Window object and created a triangle using three Points.

Window myWin = new Window(500, 500);
Point pt1 = new Point(250, 30);                
Point pt2 = new Point(360, 250);                
Point pt3 = new Point(140, 250);
Triangle trg = new Triangle (pt1, pt2, pt3);

Next, I added a Timer class that tracked the x and y coordinates of the triangle, changed its size, and increased its speed.

Timer move = new Timer(5, new ActionListener(){                
   public void actionPerformed(ActionEvent e){
      int x = triangle.getX();
      int y = triangle.getY();                                                    
      if (x <=-100 || x >= 600){
         speed *= -1;
         if (x<= -100){
            trg.translate(600,0); 
         }
      }              
      x += speed;
      trg.translate(x, y+2); //moving the triangle }  
});

Finally, I added a couple of lines of code to set up the background and draw the triangle.

Graphics g = myWin.getPaintBrush();
// Draw Background 
g.setColor(Color.BLUE);
g.fillRect(0, 0, 500, 500);
// Draw Triangle 
g.setColor(Color.YELLOW);
g.fillPolygon(trg.getXPoints(), trg.getYPoints(), 3);

The result is a triangle of varying size that travels across a static blue sky. It was neat to see everything come together and watch the triangle move. I learned a lot from this project and I highly recommend it to anyone interested in graphical animations.

Leave a Comment