我正在组装一个非常简单的2d游戏。我有一个planet类,游戏使用数组创建多个行星。我的问题是,我希望每个行星都有多个卫星,并且卫星的位置/行为与其特定母星中包含的变量相关。
什么是构造类和实例化对象的最好方法,这样就可以很容易地引用哪些卫星与哪些行星相关,并且这些卫星在游戏中可以很容易地引用其行星的变量?
发布于 2013-04-22 21:16:03
您可以将您的卫星设置为父行星的Observers,并让父行星发布卫星订阅的事件。这是一个代码草图(警告:不是完全可运行的代码):
import java.util.Observable; //Observable is here
public class Planet extends Observable implements Runnable {
public void run() {
try {
while (true) {
//do planet stuff
setChanged();
notifyObservers(response);
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
import java.util.Observable;
import java.util.Observer; /* this is Event Handler */
public class Moon implements Observer {
//setup moon instance
public void update(Observable obj, Object arg) {
//udate moon params
}
}
//
public class GameApp {
public static void main(String[] args) {
//configure game board...
final Planet earth = new Planet();
final Planet saturn = new Planet();
// create an observer
final Moon moon = new Moon();
final Moon tethys = new Moon();
final Moon titan = new Moon();
// subscribe the observer to the event source
earth.addObserver(moon);
saturn.addObserver(tethys);
saturn.addObserver(titan);
// fire up the game ...
}
}
https://stackoverflow.com/questions/16147399
复制相似问题