Note that there are some explanatory texts on larger screens.

plurals
  1. POCreating a "bullet" class (Java/swing)
    primarykey
    data
    text
    <p>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.</p> <p>I've been trying to copy: <a href="https://stackoverflow.com/questions/11574341/move-object-along-a-straight-line">this example</a>, <strong>but I can't make my bullet move smoothly towards the target location</strong></p> <pre><code>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); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload