Java 如何从数组列表更改对象的属性?

Java 如何从数组列表更改对象的属性?,java,arrays,arraylist,Java,Arrays,Arraylist,基本上,我正在用java创建一个自顶向下的shooter,对于项目符号,有一个具有所有属性和更新方法的项目符号对象。我决定在按下鼠标并创建对象实例后,使用数组列表来存储项目符号。问题是我不知道如何识别数组列表中的元素。以下是我使用简单数组时的一些代码片段: addMouseListener(new MouseAdapter(){ public void mousePressed(MouseEvent e){ pressedX = e.getX(); pre

基本上,我正在用java创建一个自顶向下的shooter,对于项目符号,有一个具有所有属性和更新方法的项目符号对象。我决定在按下鼠标并创建对象实例后,使用数组列表来存储项目符号。问题是我不知道如何识别数组列表中的元素。以下是我使用简单数组时的一些代码片段:

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

但是,在您给出的代码中,我们可以做得更好

因此:

现在它仍然直接访问项目符号中的字段,这对我来说不是个好主意。我建议您要么使用
dx
dy
的属性,要么可能使用一个单独的属性获取
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));
    }
}
您可以更改如下任何内容:

bullets[index].foo

但是,在您给出的代码中,我们可以做得更好

因此:

现在它仍然直接访问项目符号中的字段,这对我来说不是个好主意。我建议您要么使用
dx
dy
的属性,要么可能使用一个单独的属性获取
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));
    }
}

你想识别什么,一个特定的子弹?你想识别什么,一个特定的子弹?谢谢我会给这个测试!!乔恩·斯基特你是我的英雄!!真是一种享受!谢谢你的帮助!!谢谢,我会给这个做个测试!!乔恩·斯基特你是我的英雄!!真是一种享受!谢谢你的帮助!!