整体实现思路
在Android studio中新建一个游戏界面,并构建一个主线程MySurfaceView构建框架,然后分别建背景、玩家飞机、地方飞机、玩家子弹、敌方子弹、爆炸、爆炸声音的类,并在MySurfaceView调用.
1.如何绘制循环滚动的背景
将同一张图定义成两个对象,让第一个对象填满屏幕,当第一个对象到末尾时,第二个立即跟上末尾,替换第一张,第一个返回到第二个的位置继续
package com.example.a22088.lay;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
public class BackGround {
private int y1;
private int y2;
private Bitmap bitmap;
public BackGround(Bitmap bitmap){
this.bitmap = bitmap;
y1 = 0;
y2 = y1-bitmap.getHeight();
}
public void draw(Canvas canvas, Paint paint){
logic();
canvas.drawBitmap(bitmap,0,y1,paint);
canvas.drawBitmap(bitmap,0,y2,paint);
}
public void logic(){
y1+=10;
y2+=10;
if (y1>=MySurfaceView.height){
y1=y2-bitmap.getHeight();//移动到第二张图片的顶部
}
if (y2>=MySurfaceView.height){
y2=y1-bitmap.getHeight();
}
}
}
然后在MySurfaceView中调用
BackGround backGround = new BackGround(BitmapFactory.decodeResource(getResources(),R.mipmap.bk));
2.如何绘制飞机
建立Myplane和BossPlane类,利用if语句和for循环和onTouchEvent和isCollision和noisCollision和noisCollisioncount等实现飞机的飞行移动,并可以实现屏幕触摸,还创建hp,来实现飞机血量的减少。还要利用isCrazy,time,count实现boss飞机的疯狂模式时间。并在MySurfaceView中调用。
//myplane
package com.example.a22088.lay;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.MotionEvent;
public class MyPlane {
private Bitmap bitmap;
private Bitmap bitmapHp;
private int x,y;
public static int width;
public static int height;
private boolean noCollision;
private int noCollisionCount;
private int hp = 3;
public MyPlane(Bitmap bitmap,Bitmap bitmapHp){
this.bitmap = bitmap;
this.bitmapHp = bitmapHp;
x = MySurfaceView.width/2-bitmap.getWidth()/2;
y = MySurfaceView.height-bitmap.getHeight();
width = bitmap.getWidth();
height = bitmap.getHeight();
}
public void draw(Canvas canvas, Paint paint){
if (hp<0){
MySurfaceView.GAME_STATE = 1;
}
if (noCollision){
noCollisionCount++;
if (noCollisionCount%10==0){
canvas.drawBitmap(bitmap,x,y,paint);//飞机闪烁
}
if (noCollisionCount>100){
//无敌时间
noCollision = false;
noCollisionCount = 0;
}
}else {
//非无敌状态
canvas.drawBitmap(bitmap,x,y,paint);
}
for (int i =0;i<hp;i++){
canvas.drawBitmap(bitmapHp,i*bitmapHp.getWidth(),MySurfaceView.height-bitmapHp.getHeight(),paint);
}
}
public void touchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_MOVE) {
float ex = event.getX();
float ey = event.getY();
if (ex > x && ex < x + width && ey > y && ey < y + height) {
x = (int) ex - width / 2;
y = (int) ey - height / 2;
if (y < 0) {
y = 0;
}
if (y + height > MySurfaceView.height) {
y = MySurfaceView.height - height;
}
if (x < 0) {
x = 0;
}
if (x + width > MySurfaceView.width) {
x = MySurf