//I am trying to create a basic race car in java. I made a rectangle for the body and now I am trying to make a triangle for the front. I looked online for code on creating a triangle but none of it looks like it is in the format as I have for the rectangle I have below. I got most of this code from “Video Game Programming for the Evil Genius” as a reference and now we are encouraged to create our own vehicle, but rectangles are the only shapes explained. I did copy the code from the rectangle to triangle expecting one to overlap the other, just so that I knew it worked, but it’s not. Would anyone be able to explain to me how to make a triangle and possibly a circle? Also is there anyway of doing this without having to create another class?
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
public class Vehicle extends JFrame
{
final int WIDTH = 900; int HEIGHT = 650;
Rectangle p1Body = new Rectangle(WIDTH/9,HEIGHT/2, WIDTH/30,WIDTH/30);
Triangle p1Front = new Triangle(WIDTH/9,HEIGHT/2, WIDTH/30,WIDTH/30);
Rectangle p2Body = new Rectangle(((WIDTH/9)+((int)((WIDTH/9)*1.5)/2)),(HEIGHT/2)+
(HEIGHT/10),WIDTH/30,WIDTH/30);
public Vehicle()
{
super("Radical Racing");
setSize(WIDTH,HEIGHT);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public void paint(Graphics g)
{
super.paint(g);
g.setColor(Color.DARK_GRAY);
g.fillRect(0,0,WIDTH,HEIGHT);
g.setColor(Color.BLUE);
g.fill3DRect(p1Body.x,p1Body.y,p1Body.width,p1Body.height,true);
g.setColor(Color.BLUE);
g.fill3D(p1Front.x,p1Front.y,p1Front.width,p1Front.height,true);
g.setColor(Color.red);
g.fill3DRect(p2Body.x,p2Body.y,p2Body.width,p2Body.height,true);
}
public static void main(String[]args)
{
new Vehicle();
}
}
Triangle can be done using Path2D(.Double) circle can be done using Ellipse2D(.Double)
BTW, you might want to think about combining all of these shapes into one using Area – http://docs.oracle.com/javase/7/docs/api/java/awt/geom/Area.html. Area is very useful for manipulating shapes & testing if they contain a point etc.
Check out Graphics2D.draw (or fill) (Shape)
http://docs.oracle.com/javase/7/docs/api/java/awt/Graphics2D.html#draw(java.awt.Shape)