如何让对象访问其调用对象的变量并修改它们?

时间:2016-02-01 23:52:46

标签: java oop parameters constructor

说我有一个2d侧视型游戏。在这个游戏中我有精灵和其他物体。单击空格键时精灵会跳转。跳跃和其他事情都受到重力的影响。我有一个Gravity类需要x&的参数。它正在影响的对象的y坐标。当它从Sprite类构造时,我会将sprite位置的x和y作为参数给它。然后,引力类进行必要的数学计算,现在有一个修改过的x& y坐标。如何更新旧版x& y在Sprite类(调用类)中由Gravity计算的新坐标对(需要修改Sprite中的变量的对象)?

额外信息: x& y变量不能是静态的。这一切都在当前的一个线程上(除了绘制的图形线程)。如果需要,我可以制作更多线程。我在重力类中有一个摆动计时器,它在创建对象时开始,用于计算坐标作为时间,速度,加速度等的影响。

重力类代码:

import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Timer;

public class Gravity implements ActionListener { 

    final double gravAccel = -32.174;
    double velocity; // in FPS
    double angle; // in degrees
    double x; // centralized location of object in feet
    double y; // centralized location in feet
    double time = 0;
    Timer timer;
    boolean fired = true;
    Point start;

    public Gravity(double x, double y, double velocity, double angle, Point start) {
        this.x = x;
        this.y = y;
        this.velocity = velocity;
        this.angle = angle;
        this.start = start;
        initTimer();
    }



    void initTimer() {
        timer = new Timer(10, this);
        timer.start();
    }   


    public void fire(double velocity, double angle) {
        //timer.start();
        x = (velocity * Math.cos(Math.toRadians(angle))) * time + start.getX();
        y = 0.5 * gravAccel * Math.pow(time, 2) + (velocity * Math.sin(Math.toRadians(angle))) * time + start.getY();
        System.out.println("Time:" + time + "          " + x + "," + y);

    }


    @Override
    public void actionPerformed(ActionEvent e) {
        time = time + 0.01;
        if (fired == true) {
            fire(velocity, angle);
        }

    }
}

的Sprite:

public class Sprite {
    double x = 10; //how can I modify these from gravity
    double y = 10;
    Sprite() {
       new Gravity(x, y, 100, 45, new Point(0,0));
    }
}

2 个答案:

答案 0 :(得分:1)

保留对Sprite in Gravity的引用:

private Sprite;
public Gravity(double x, double y, double velocity, double angle, Point start, Sprite sprite) {
   this.sprite = sprite;
   ...
}

并在创建它时从Sprite传递它:

Sprite() {
   new Gravity(x, y, 100, 45, new Point(0,0), this);
}

答案 1 :(得分:-1)

您可以将xy公开:

public double x = 10;
public double y = 10;

然后直接从sprite类访问它们。