我在使用Java的Android Studio中制作游戏。我遇到一个问题,我的收藏品在玩家将其收藏后仍保持在相同的位置重新生成。我希望它重新生成在屏幕上的随机位置。我怎样才能做到这一点?
收藏品是燃料罐。
这是油罐收藏类Fuel.java
public class Fuel extends GameObject {
public Fuel(Bitmap res, int w, int h, int numFrames) {
x = GamePanel.WIDTH + 5000;
y = GamePanel.HEIGHT / 2;
dy =(random.nextInt()*(GamePanel.HEIGHT - (maxBorderHeight* 2)+maxBorderHeight));
dx = +GamePanel.MOVESPEED;
height = h;
width = w;
Bitmap[] image = new Bitmap[numFrames];
spritesheet = res;
for (int i = 0; i < image.length; i++)
{
image[i] = Bitmap.createBitmap(spritesheet, 0, i*height, width, height);
}
animation.setFrames(image);
animation.setDelay(100-dx);
animation.update();
}
public void update()
{
if (x < 0) {
reset();
}
x += dx;
dx = dx- 1;
if (dx <= -15) {
dx = -15;
}
animation.update();
}
public void draw(Canvas canvas)
{
try {
canvas.drawBitmap(animation.getImage(),x,y,null);
}catch (Exception e){}
}
public void reset(){
x = GamePanel.WIDTH + 5000;
y = GamePanel.HEIGHT/2 ;
dy = (random.nextInt()*(GamePanel.HEIGHT - (maxBorderHeight* 2)+maxBorderHeight));
dx = +GamePanel.MOVESPEED;
}
public void fuelCollected(){
reset();
}
}
GamePanel.java
public class GamePanel extends SurfaceView implements SurfaceHolder.Callback
{
private Fuel fuel;
@Override
public void surfaceCreated(SurfaceHolder holder){
fuel = new Fuel(BitmapFactory.decodeResource(getResources(), R.drawable.fuel),40,40,1);
}
public void update()
{
fuel.update();
if(collectFuel(player,fuel)){
distance +=100;
}
public boolean collectFuel(GameObject player, GameObject fuel){
if(Rect.intersects(player.getRectangle(),fuel.getRectangle()))
{
fuelCollected();
return true;
}
return false;
}
public void fuelCollected(){fuel.fuelCollected();}
}
@Override
public void draw(Canvas canvas){
// draw fuel can
fuel.draw(canvas);
}
}
最佳答案
将Fuel reset()
方法更改为如下所示:
public void reset() {
x = random.nextInt(GamePanel.WIDTH);
y = random.nextInt(GamePanel.HEIGHT);
dy = (random.nextInt()*(GamePanel.HEIGHT - (maxBorderHeight* 2)+maxBorderHeight));
dx = +GamePanel.MOVESPEED;
}
假设
x, y
是整数变量,x
将是0
和GamePanel.WIDTH
之间的随机整数,而y
是0
和GamePanel.HEIGHT
之间的随机整数。为什么将
5000
添加到GamePanel.WIDTH
?关于java - 如何在Java中的随机位置生成 Collection 品,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42233783/