基本上,我正在用java创建一个自上而下的射击游戏,对于子弹来说,有一个子弹对象,其中包含所有属性和更新方法等内容。我决定在按下鼠标并创建对象实例后使用数组列表来存储项目符号。问题是我不知道如何识别数组列表中的元素。这是我仅使用简单数组时的一些代码片段:
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++;
}
非常感谢任何帮助!提前致谢!
最佳答案
您可以更改如下内容:
bullets[index].foo
至
bullets.get(index).foo
但是,在您给出的代码中,我们可以做得更好。
所以:
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);
}
}
现在仍然直接访问项目符号中的字段,这对我来说似乎不是一个好主意。我建议您使用 dx
和 dy
的属性 - 或者可能使用 Velocity
的单个属性(这基本上是 dx 和 dy 的 vector ) - 或者你将其作为构造函数的一部分:
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));
}
}
关于java - 如何更改数组列表中对象的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9753519/