我制作了2D游戏,效果很好。我决定创建一个简单的"开始屏幕"应该显示高分和"开始"应该开始游戏的按钮。
我认为我可以只使用常规意图从一个活动转到另一个活动,但它不起作用。单击"开始"然后应用程序崩溃按钮。
我使用场景管理器,因此并非所有代码都是在游戏面板中编写的。
这是我的MainActivity
package com.example.korisnik_pc.a2dgame;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
Button button;
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // MAKE IT FULLSCREEN
this.requestWindowFeature(Window.FEATURE_NO_TITLE); // REMOVES TOOLBAR
// setting the screen dimensions
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
Constants.SCREEN_HEIGHT = dm.heightPixels;
Constants.SCREEN_WIDTH = dm.widthPixels;
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, GamePanel.class);
startActivity(intent);
}
});
}
游戏小组
public class GamePanel extends SurfaceView implements SurfaceHolder.Callback {
private MainThread thread;
private SceneManager sceneManager;
public GamePanel(Context context) {
super(context);
getHolder().addCallback(this);
thread = new MainThread(getHolder(), this);
sceneManager = new SceneManager();
setFocusable(true);
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
thread = new MainThread(getHolder(), this);
thread.setRunning(true);
thread.start();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
while (true) {
try {
thread.setRunning(false);
thread.join();
} catch (Exception e) {
e.printStackTrace();
}
retry = false;
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
sceneManager.receiveTouch(event);
return true;
}
public void update() {
sceneManager.update();
}
public void draw(Canvas canvas) {
super.draw(canvas);
sceneManager.draw(canvas);
}
}