试图在滚动背景上创建一个移动的精灵

时间:2016-08-14 09:15:54

标签: java android

我对Android感兴趣,我是新手,因此我创建了一个滚动背景,我想在其上放一个精灵,我已经创建了一个角色类和滚动背景。我想让精灵向右移动,但我在GamePanel上遇到错误。

错误是非静态方法(android.graphics.Canvas)无法从静态上下文中引用,它是什么意思,我将如何解决这个问题,并使我的精灵看起来像向右跑? / p>

这是我的代码:

public class GamePanel extends SurfaceView implements SurfaceHolder.Callback {

public static final int WIDTH = 856;
public static final int HEIGHT = 480;
public static int Score =0;
public static int Highscore;
private MainThread thread;
private Background bg;
private Bitmap bmp;

public GamePanel(Context context) {
    super(context);
    getHolder().addCallback(this);
    thread = new MainThread(getHolder(), this);
    setFocusable(true);

}

@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) {
    bg = new Background(BitmapFactory.decodeResource(getResources(), R.drawable.gamebg));
    bmp = BitmapFactory.decodeResource(getResources(), R.drawable.deer);
    bg.setVector(-5);
    thread.setRunning(true);
    thread.start();
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    return super.onTouchEvent(event);
}
public void update() {
    Score += 2;
    if (Score > Highscore) {
        Highscore = Score;
    }
    bg.update();
}
@SuppressLint("MissingSuperCall")
@Override
public void draw(Canvas canvas) {
    final float scaleFactorX = (float)getWidth()/WIDTH;
    final float scaleFactorY = (float)getHeight()/HEIGHT;
    if(canvas !=null) {
        final int savedState = canvas.save();
        canvas.scale(scaleFactorX, scaleFactorY);
        bg.draw(canvas);
        canvas.restoreToCount(savedState);

        Paint textpaint = new Paint();
        textpaint.setTextSize(30);
        canvas.drawText("Score:" +String.valueOf(Score), 0, 32, textpaint);
        canvas.drawText("High Score: "+String.valueOf(Highscore), 0, 64, textpaint);

    }
}
@Override
protected void onDraw(Canvas canvas) {
    Character.onDraw(canvas);
}

}

1 个答案:

答案 0 :(得分:0)

您无法从静态上下文访问非静态方法。因此,如果要访问GamePanel类的函数或对象,则需要使用GamePanel类的对象实例来调用此成员。

只是一个例子:

<强>错误:

GamePanel.draw(canvas);

<强>正确的:

GamePanel gamePanel = new GamePanel(this);
gamePanel.draw(canvas);