0

I'm trying to create a Tower Defense style game, where the object is to stop the attacking forces from reaching their target. This is done by building towers, which attacks the waves of enemies with different kinds of attacks. As I am new to programming, I was hoping for some help with creating my bullet's SetBulletLocation method.

I've been trying to copy: this example, but I can't make my bullet move smoothly towards the target location

public class Bullets extends JComponent{
//x,y = the towers coordinates, where the shoot initiliazes from.
//tx, ty = Target's x and y coordinates.
private int x,y,tx,ty;
private Point objectP = new Point();
    public Bullets(int x, int y, int tx, int ty)
        this.x = x;
        this.y = y;
        this.tx = tx;
        this.ty = ty;
        setBounds(x,y,50,50);
        //Create actionlistener to updateposition of the bullet (setLocation of component)
        ActionListener animate = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {

            setBulletLocation();


        }
        };
        Timer t = new Timer(500,animate);
        t.start();

    }
public void setBulletLocation() {
    objectP = this.getLocation();
    double xDirection =  5* Math.cos(-(Math.atan2(tx - x, tx - y))+ 90);
    double yDirection =  5* Math.sin(-(Math.atan2(tx - x, tx - y))+ 90);
    System.out.println(xDirection + " , " + yDirection);
    x = (objectP.x + (int) xDirection);
    y = (objectP.y + (int) yDirection);
    setLocation(x, y);

    repaint();
 }
@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.fillOval(0, 0, 50, 50);
}
Community
  • 1
  • 1
  • Where in your code is the 500ms (or is it ns) applied to move the bullet? – Richard Tingle Jul 02 '13 at 13:23
  • All of the objects in your game should be GUI models. You should have one JPanel that you use as a canvas. That one JPanel draws all of the game objects to create one frame of animation. – Gilbert Le Blanc Jul 02 '13 at 14:15

3 Answers3

2

All the Java math trig functions take radians for angular arguments, not degrees. Try Math.PI/2 instead of 90 in:

double xDirection = 5* Math.cos(-(Math.atan2(tx - x, tx - y))+ 90);

double yDirection = 5* Math.sin(-(Math.atan2(tx - x, tx - y))+ 90);

Community
  • 1
  • 1
lreeder
  • 12,047
  • 2
  • 56
  • 65
1

I noticed there is error in calculating displacement

fragment:

Math.atan2(tx - x, tx - y))

didn't you mean ?:

Math.atan2(tx - x, ty - y))
user1387886
  • 122
  • 1
  • 7
0

Your paintComponent() seems to be painting the bullet in the same location and size every time regardless of your calculations.

Store your new x and new y values into member variables and use those in paintComponent.

Also - the Java's trig functions use radians, not degrees so update your references to 90 degrees with pi / 2.

clyde
  • 824
  • 9
  • 18