0

Basically, I am creating a top down shooter in java, and for the bullets there is a bullet object with all the properties and update methods and stuff. I hava decided to use an array list to store the bullets in once the mouse is pressed and an instance of the object has been created. The problem is that I do not know how to identify elements in an array list. Here is a snippet of some of the code when i was using just a simple array:

addMouseListener(new MouseAdapter(){
    public void mousePressed(MouseEvent e){
        pressedX = e.getX();
        pressedY = e.getY();


        bullets[bulletCount] = new Bullet(player.x, player.y));
        double angle = Math.atan2((pressedY - player.y),(pressedX - player.x));
    bullets[bulletCount].dx = Math.cos(angle)*5;
    bullets[bulletCount].dy = Math.sin(angle)*5;
    bulletCount++;  


    }

Any help is greatly appreciated! Thanks in advance!

1
  • what are you trying to identify, a specific bullet? Commented Mar 17, 2012 at 20:39

1 Answer 1

3

You could just change anything like this:

bullets[index].foo

to

bullets.get(index).foo

However, in the code you've given, we can do better.

So:

addMouseListener(new MouseAdapter() {
    public void mousePressed(MouseEvent e) {
        int pressedX = e.getX();
        int pressedY = e.getY();

        Bullet bullet = new Bullet(player.x, player.y);
        double angle = Math.atan2((pressedY - player.y), (pressedX - player.x));
        bullet.dx = Math.cos(angle)*5;
        bullet.dy = Math.sin(angle)*5;
        bullets.add(bullet);
    }
}

Now that's still accessing fields in the bullet directly, which doesn't seem like a very good idea to me. I would suggest that you either use properties for dx and dy - or possibly a single property taking a Velocity (which would basically be a vector of dx and dy) - or you make that part of the constructor:

addMouseListener(new MouseAdapter() {
    public void mousePressed(MouseEvent e) {
        // Again, ideally don't access variables directly
        Point playerPosition = new Point(player.x, player.y);
        Point touched = new Point(e.getX(), e.getY());

        // You'd need to put this somewhere else if you use an existing Point
        // type.
        double angle = touched.getAngleTowards(playerPosition);
        // This method would have all the trigonometry.
        Velocity velocity = Velocity.fromAngleAndSpeed(angle, 5);

        bullets.add(new Bullet(playerPosition, velocity));
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Jon Skeet you're my hero!! Works a treat! Thanks for the help!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.