我使用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);
}
}
答案 0 :(得分:1)
将燃料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
?