Reputation: 1
I am trying to make a bullet class. When it is called it will get a direction and an initial position. The problem is the direction is not working it only goes up no matter what I set as the direction.
Please Help.
Thanks in advance
public class Bullet extends JComponent implements ActionListener{
private int bx,by;
private double theta;
private double BvelX, BvelY;
private Timer timer = new Timer(8,this);
public Bullet(int bx, int by, double theta)
{
this.bx = bx;
this.by = by;
this.theta = theta;
BvelX = 0;
BvelY = -1;
timer.start();
revalidate();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D graphicsS = (Graphics2D) g;
graphicsS.rotate(theta, bx, by);
graphicsS.setColor(Color.RED);
graphicsS.fillOval(bx, by, 8, 8);
}
public void actionPerformed(ActionEvent e)
{
bx += BvelX;
by += BvelY;
/*by += 5*(Math.sin(theta));
bx += 5*(Math.cos(theta));*/
revalidate();
repaint();
}
}
Upvotes: 0
Views: 98
Reputation: 5830
your direction is right here:
BvelX = 0;
BvelY = -1;
this says go strait up
you probably want something like what is commented out
BvelY = 5*(Math.sin(theta));
BvelX = 5*(Math.cos(theta));
Since your positions are integer, you will not be able to go exactly the direction you are pointing. Maybe you should store doubles, but draw integers. Then you could get the bullet to travel closer to theta.
Upvotes: 1
Reputation: 19778
Well it goes up because:
BvelX = 0;
BvelY = -1;
And when you update:
bx += BvelX;
by += BvelY;
So y
is decremented (so it goes up) but x
always stays the same (so it doesn't go left or right)
Upvotes: 0