2017-02-14 81 views
0

我使用Java在Android Studio中製作遊戲。我有一個問題,我的收藏品在玩家收集完畢後會在同一個位置重新產卵。我想讓它在屏幕上的隨機位置重新產卵。我怎樣才能做到這一點?如何在Java中隨機位置產生收藏品

收藏品是一種燃料罐。

這裏是燃料罐收藏類

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

請僅發佈相關代碼,說明它在做什麼與您希望做什麼。它只是「重置」方法嗎? – alfasin

回答

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是整數變量x0GamePanel.HEIGHT之間0GamePanel.WIDTHy一個隨機整數之間的隨機整數。 爲什麼添加5000GamePanel.WIDTH

+0

謝謝讓我試一下這個代碼,+5000是一種延遲,所以收集的產物會離開屏幕,需要一些時間讓玩家看到它 – Kennedy

+0

感謝它的工作 – Kennedy