我的2d安卓游戏有问题

时间:2016-06-11 11:44:14

标签: java android random 2d-games android-studio-2.1

嘿,伙计我是一个菜鸟,所以不要和我一起努力。 我正在开发Android的2D游戏我遇到了一些麻烦。 它几乎完成了,但我想在我的游戏中收集可收集的硬币,我希望它们在我的障碍物上随机产生。我已经完成了硬币的主要代码,他们正在我的障碍物上盘旋,你可以收集它们,但我不知道如何让它们随机产生:我希望你能帮助我这里是我的代码: 我的硬币类:

enter code herepublic class Coin  extends GameObject{
private Bitmap spritesheet;
private double dya;
private boolean playing;
private long startTime;
private Animation animation = new Animation();
private int num = 0;
private Obsticals obsticals;

public Coin(Bitmap res, int w, int h, int numFrames) {
    x = GamePanel.WIDTH + 20;
    y = GamePanel.HEIGHT - GamePanel.HEIGHT / 4 - 200;
    dy = 0;
    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, i*width, 0, width, height);
    }
    animation.setFrames(image);
    animation.setDelay(100);

}
public void update()
{
        if (y <= 50) {
            resetO();
        }
        x += dx;
        long elapsed = (System.nanoTime() - startTime) / 1000000;
        if (elapsed > 10000) {
            dx = dx - 1;
            startTime = System.nanoTime();
            System.out.println(dx);
            num = num + 30;
        }
        if (dx <= -25) {
            dx = -24;
        }
        if (num >= 200) {
            num = 200;
        }

}
public void draw(Canvas canvas)
{
    canvas.drawBitmap(animation.getImage(),x,y,null);


}
public void resetO(){
    x = GamePanel.WIDTH + 20;
    y = GamePanel.HEIGHT - GamePanel.HEIGHT / 4 - 200;
    dy = 0;
    dx = +GamePanel.MOVESPEED;
    num = 0;

}
public void coinCollected(){

   resetO();
}


}

这是我的游戏面板代码:

公共类GamePanel扩展了SurfaceView实现的SurfaceHolder.Callback {

public static final int WIDTH = 856;
public static final int HEIGHT = 480;
public static int MOVESPEED = -15;

//other classes
private MainThread thread;
private background bg;
private busch busch;
private Ground ground;
private Player player;
private Obsticals obsticals;
private sun sun;
private Coin coin;
private CoinSymbol coinSymbol;

private Random rand = new Random();

public boolean sliden = false;

private int coinCounter = 0;

//SharedPreferences for coins
SharedPreferences coinprefs;
SharedPreferences.Editor coinprefsEditor;

// SharedPreferences for highscore
SharedPreferences prefs;
SharedPreferences.Editor prefsEditor;
int highscore;
int Highstring;
final String KEY1 = "key1";

public enum STATE{
    MENU,
    INGAME,
    GAMEOVER;
};
private STATE State = STATE.MENU;

public GamePanel(Context context) {

    super(context);
    //add the callback to the surfaceholder to intercept events
    getHolder().addCallback(this);

    coinprefs = context.getSharedPreferences("Coinprefsdatei", Context.MODE_PRIVATE);
    coinprefsEditor = coinprefs.edit();

    prefs = context.getSharedPreferences("prefsdatei", Context.MODE_PRIVATE);
    prefsEditor = prefs.edit();

    thread = new MainThread(getHolder(), this);

    //make gamePanel focusable so it can handle events
    setFocusable(true);
}
public void GameOver(){
    State = STATE.GAMEOVER;
}
public   void newgame(){
    MOVESPEED = -15;
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {
    boolean retry = true;
    while (retry) {
        try {
            thread.setRunning(false);
            thread.join();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        retry = false;
    }

}

@Override
public void surfaceCreated(SurfaceHolder holder) {
    //checkt highscore
    loadScore();
    loadCoins();
    //malt alle bilder
    sun = new sun(BitmapFactory.decodeResource(getResources(), R.drawable.sonne));
    bg = new background(BitmapFactory.decodeResource(getResources(), R.drawable.baum));
    busch = new busch(BitmapFactory.decodeResource(getResources(), R.drawable.applandschaft));
    ground = new Ground(BitmapFactory.decodeResource(getResources(), R.drawable.weg));
    coinSymbol = new CoinSymbol(BitmapFactory.decodeResource(getResources(), R.drawable.coinsymbol));
    //Breite, Höhe, Frames
    player = new Player(BitmapFactory.decodeResource(getResources(), R.drawable.test), 115, 120, 8);
    obsticals = new Obsticals(BitmapFactory.decodeResource(getResources(), R.drawable.hindernisnew), 75, 150, 1);
    coin = new Coin(BitmapFactory.decodeResource(getResources(), R.drawable.coin), 40, 40, 4);
    //we can safely start the game loop
    thread.setRunning(true);
    thread.start();

}
public void saveHighscore(){
    highscore = player.getScore();
    prefsEditor.putInt(KEY1,highscore);
    prefsEditor.commit();
}
public void loadScore(){
    Highstring = prefs.getInt(KEY1,0);
}
public void loadCoins() { coinCounter = coinprefs.getInt(KEY1,0); }
public void saveCoins() {
    coinprefsEditor.putInt(KEY1,coinCounter);
    coinprefsEditor.commit();
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    if(event.getAction()==MotionEvent.ACTION_DOWN){
        if(State == STATE.MENU){
            State = STATE.INGAME;

        }
        if(!player.getPlaying() && State == STATE.INGAME)
        {
            player.setPlaying(true);

        }
        else if (State == STATE.INGAME)
        {
            player.setUp(true);
        }
        else if (State == STATE.GAMEOVER)
        {
            player.resetScore();
            player.resetP();
            player.setPlaying(true);
            State = STATE.INGAME;
            obsticals.resetO();
            coin.resetO();
            //newgame();
        }
        return true;

    }
    if(event.getAction()==MotionEvent.ACTION_UP)
    {
        player.setUp(false);
        return true;
    }

    return super.onTouchEvent(event);
}

public void update() {
    if (player.getPlaying() == true && State == STATE.INGAME) {
        bg.update();
        busch.update();
        player.update();
        ground.update();
        obsticals.update();
        coin.update();
        collisionboolen(player, obsticals);
        collectCoin(player, coin);
   }
    }

public boolean collisionboolen(GameObject player, GameObject obsticals)
{
    if(Rect.intersects(player.getRectangle(),obsticals.getRectangle()))
    {
        checkScore();
        saveCoins();
        State = STATE.GAMEOVER;
        ground.restartGround();
        return true;


    }
    return false;
}
public boolean collectCoin(GameObject player, GameObject coin)
{
    if(Rect.intersects(player.getRectangle(),coin.getRectangle()))
    {
        coidcollectet();
        coinCounter += 1;
        return true;
    }
    return false;
}
public void coidcollectet(){coin.coinCollected();}
public void stopPlay(){
    player.setPlaying(false);

}
public void checkScore(){
    if (player.score > Highstring)
    {
        saveHighscore();
        loadScore();
    }else {
        loadScore();
    }
}
public void startMusik(){

}

@Override
public void draw(Canvas canvas) {
    final float scaleFactorX = getWidth() / (WIDTH*1.f);
    final float scaleFactorY = getHeight() / (HEIGHT*1.f);
    if (canvas != null && State == STATE.INGAME) {
        final int savedState = canvas.save();

        canvas.scale(scaleFactorX, scaleFactorY);
        sun.draw(canvas);
        Paint paint = new Paint();
        paint.setColor(Color.BLACK);
        paint.setTextSize(50);
        paint.setTextAlign(Paint.Align.RIGHT);
        canvas.drawText(""+coinCounter, WIDTH - 50 , 50 , paint);
        bg.draw(canvas);
        coinSymbol.draw(canvas);
        busch.draw(canvas);
        ground.draw(canvas);
        player.draw(canvas);
        obsticals.draw(canvas);
        coin.draw(canvas);
        canvas.restoreToCount(savedState);


    }else if (canvas != null && State == STATE.MENU){

        canvas.scale(scaleFactorX, scaleFactorY);
        sun.draw(canvas);
        bg.draw(canvas);
        coinSymbol.draw(canvas);
        busch.draw(canvas);
        ground.draw(canvas);
        Paint paint = new Paint();
        paint.setColor(Color.BLACK);
        paint.setTextSize(100);
        paint.setTextAlign(Paint.Align.CENTER);
        canvas.drawText("Start Game", WIDTH / 2  , HEIGHT / 2 , paint);
        paint.setColor(Color.BLACK);
        paint.setTextSize(50);
        canvas.drawText("touch to start!", WIDTH / 2  , HEIGHT / 2 + 100 , paint);
        paint.setTextAlign(Paint.Align.RIGHT);
        canvas.drawText(""+coinCounter, WIDTH - 50  , 50 , paint);
        paint.setTextAlign(Paint.Align.CENTER);
        paint.setTextSize(20);
        canvas.drawText("Highscore = "+Highstring, WIDTH / 2  , HEIGHT / 2 + 150 , paint);


    }else if (canvas != null && State == STATE.GAMEOVER){

    canvas.scale(scaleFactorX, scaleFactorY);
        canvas.drawColor(Color.BLACK);
        sun.draw(canvas);
        bg.draw(canvas);
        coinSymbol.draw(canvas);
        busch.draw(canvas);
        ground.draw(canvas);
        Paint paint = new Paint();
        paint.setColor(Color.BLACK);
        paint.setTextSize(100);
        paint.setTextAlign(Paint.Align.CENTER);
        canvas.drawText("GAME OVER", WIDTH / 2  , HEIGHT / 2 , paint);
        paint.setTextSize(50);
        canvas.drawText("touch to restart!", WIDTH / 2  , HEIGHT / 2 + 100 , paint);
        paint.setTextAlign(Paint.Align.RIGHT);
        canvas.drawText(""+coinCounter, WIDTH -50  , 50 , paint);
        paint.setTextAlign(Paint.Align.CENTER);
        paint.setTextSize(20);
        canvas.drawText("Highscore = "+Highstring, WIDTH / 2  , HEIGHT / 2 + 150 , paint);




    }
}
}

我希望你能帮助我!

1 个答案:

答案 0 :(得分:0)

这是一个将球产生到随机位置的功能。希望您能适应您的需求:

public void spawn() {
    /**
     * Spawns the ball at a random position
     */
    Random random = new Random();

    radius = random.nextFloat() * 100f + 50f;

    float velocity_x = random.nextFloat() * 70.0f + 40.0f;
    float position_y = random.nextFloat() * (screen_height - 120 - radius);

    position = new Vector(screen_width, position_y);
    paused_velocity = velocity = new Vector(-velocity_x, 0.0f);

}

来源:Virajmahesh | GitHub:落球