Reputation: 81
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!
Upvotes: 0
Views: 1859
Reputation: 1503280
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));
}
}
Upvotes: 3