Question

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);
}
Was it helpful?

Solution

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);

OTHER TIPS

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))

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top