关于这个话题还有其他的问题,但这个问题在某种程度上不同。
基本上,我有一个叫做"Player“的类,我把它乘以一定的次数。该类在画布中生成随机坐标,位图向这些坐标移动。现在的问题是,它们中的一些相互重叠,使之看起来“不现实”。
我在"Player“类中尝试了一个简单的"if”语句,但它不起作用,因为类的每个实例只计算其变量,而忽略了其他实例的变量。
下面是代码:
我有第一个类,还有一个嵌套的类:
public class MainActivity extends Activity{
Game gameView;
float k,l;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gameView = new Game(this);
setContentView(gameView);
}
public class Game extends SurfaceView implements Runnable {
Canvas canvas;
SurfaceHolder ourHolder;
Thread ourThread = null;
boolean isRunning = true;
Player[] player = new Player[3];
public Game(Context context) {
super(context);
ourHolder = getHolder();
ourThread = new Thread(this);
ourThread.start();
for(int i=0; player.length < i; i++){
player[i] = new Player(context);
}
}
public void run() {
while(isRunning) {
if(!ourHolder.getSurface().isValid())
continue;
canvas = ourHolder.lockCanvas();
canvas.drawRGB(200, 200, 200);
for ( int i = 0; player.length < i; i++){
player[i].draw(canvas);
player[i].move();
}
ourHolder.unlockCanvasAndPost(canvas);
}
}
}
}这是玩家的课程:
public class Player {
Bitmap base;
float x = (float) (Math.random()*200);
float y = (float) (Math.random()*200);
float e = (float) (Math.random()*200);
float r = (float) (Math.random()*200);
public Player(Context context) {
super();
base = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher);
}
public void draw(Canvas canvas) {
if(x > e-5 && x < e+5 && y > r-5 && y < r+5){
e = (float) (Math.random()*canvas.getWidth());
r = (float) (Math.random()*canvas.getHeight());
}
canvas.drawBitmap(base, x - base.getWidth()/2, y - base.getHeight()/2, null);
}
public void move () {
//Here's just the code that makes the bitmap move.
}
}正如您可能已经看到的,变量"e“和"r”在位图的坐标(x和y)接近它们时创建随机值,然后"x“和"y”变量增加或减小它们的值,以匹配"e“和"r”坐标。
现在,我希望变量"x“和"y”与其他实例的变量"x“和"y”相互作用,这样它们就不会重叠。有办法吗?
非常感谢。
发布于 2014-09-29 23:02:26
在您的Player类中,要么使X和Y公开(不推荐),要么为它们创建访问器:
public void setX(float x) {
this.x = x;
}和
public int getX() {
return x;
}现在,在run()方法中,您可以这样做(借用您已经拥有的代码):
for ( int i = 0; player.length < i; i++){
player[i].draw(canvas);
player[i].move();
}
...
for (int i = 0; i < player.length - 1; i++) {
if (player[i].getX() > player[i + 1].getX() - 5 &&
player[i].getX() < player[i + 1].getX() + 5 &&
player[i].getY() > player[i + 1].getY() - 5 &&
player[i].getY() < player[i + 1].getY() + 5) {
// Do your update here!
// You may need to create other methods...or you can just
// create random X & Y for the player.
}这是一个非常简单的方法。记住,如果你有很多玩家,你可以将一个球员移到另一个玩家身上,所以你可能想在移动玩家后再测试一次,以确保它是清晰的。
https://stackoverflow.com/questions/26110012
复制相似问题