2012-03-17 100 views
0

基本上,我在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++; 


    } 

任何帮助,非常感谢!提前致谢!

+0

你想找什么,一个特定的子弹? – twain249 2012-03-17 20:39:30

回答

3

可以只是改变这样的事:

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

现在仍然访问领域直接子弹,这似乎不是一个很好的主意给我。我建议你要么使用属性dxdy - 或者可能是一个财产采取Velocity(这主要是dx和dy的载体) - 或你做的构造函数的一部分:

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)); 
    } 
} 
+0

谢谢我会给这个测试! – hazard1994 2012-03-17 20:41:16

+0

Jon Skeet你是我的英雄!作品一种享受!谢谢您的帮助!! – hazard1994 2012-03-17 20:47:05

+0

好的谢谢你的额外帮助! – hazard1994 2012-03-17 20:49:55

相关问题