다른 클래스에서 SurfaceView에 액세스하는 방법은 무엇입니까?
우주선이 왼쪽이나 오른쪽으로 이동하고 총알을 발사 할 수있는 아주 간단한 촬영을 시도하고 있습니다. 나는 이것을 멀리 보았고, 내가 물건과 타입의 배치에 엉망이되었을지도 모른다는 것을 깨달았다. 우주선과 버튼은 현재 RelativeLayout 내의 ImageViews입니다. 스타 배경은 SurfaceView 내 유일한 것입니다. 실제로는 "배경"이 아니지만 무작위로 생성 된 비트 맵이므로 움직이는 것처럼 보입니다.
더 많은 개체를 만들어야합니다 : 글 머리 기호와 적. 가장 큰 문제는 총알이 우주선에서 발사되도록 우주선 좌표에 액세스해야한다는 것입니다.
내가 잘못 했니? 대신 버튼을 SurfaceView에 비트 맵으로 그려야합니까? 이 작업을 수행하는 가장 좋은 방법을 알고 싶습니다.
현재 상태에서 우주선이 왼쪽에서 오른쪽으로 원활하게 이동하고 단추가 색상을 전환하여 사운드를 재생합니다. 문제는이 자체을 할 수있는 "적절한"방법 인 경우
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import java.util.Random;
public class MainActivity extends Activity {
GameView gameView;
FrameLayout game;
RelativeLayout widgets;
ImageButton leftButton;
ImageButton rightButton;
ImageButton leftFireButton;
ImageButton rightFireButton;
ImageView ship;
float shipX;
MediaPlayer mp;
static final int leftButtonID = 1;
static final int rightButtonID = 2;
static final int leftFireButtonID = 3;
static final int rightFireButtonID = 4;
static final int laserId = 5;
SoundPool soundPool;
int soundID;
//Bitmap laser;
//ImageView laser;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ship = new ImageView(this);
gameView = new GameView(this);
game = new FrameLayout(this);
widgets = new RelativeLayout(this);
leftButton = new ImageButton(this);
rightButton = new ImageButton(this);
leftFireButton = new ImageButton(this);
rightFireButton = new ImageButton(this);
//laser = BitmapFactory.decodeResource(getResources(), R.drawable.laser_beam);
//laser = new ImageView(this);
leftButton.setId(leftButtonID);
rightButton.setId(rightButtonID);
leftFireButton.setId(leftFireButtonID);
rightFireButton.setId(rightFireButtonID);
//laser.setId(laserId);
//ship = BitmapFactory.decodeResource(getResources(),R.drawable.spaceship_1_80x70); //should this be an image or bitmap?
//laser.setImageResource(R.drawable.laser_beam); Should be a bitmap instead?
leftButton.setImageResource(R.drawable.left_arrow);
rightButton.setImageResource(R.drawable.right_arrow);
leftFireButton.setImageResource(R.drawable.red_button);
rightFireButton.setImageResource(R.drawable.red_button);
ship.setImageResource(R.drawable.spaceship_1_80x70);
//add views to screen
game.addView(gameView);
game.addView(widgets);
widgets.addView(leftButton);
widgets.addView(rightButton);
widgets.addView(leftFireButton);
widgets.addView(rightFireButton);
widgets.addView(ship);
leftButton.setBackgroundColor(Color.TRANSPARENT);
rightButton.setBackgroundColor(Color.TRANSPARENT);
leftFireButton.setBackgroundColor(Color.TRANSPARENT);
rightFireButton.setBackgroundColor(Color.TRANSPARENT);
mp = MediaPlayer.create(this, R.raw.bass_loop);
mp.setLooping(true);
mp.start();
loadSounds(this);
leftButton.setOnTouchListener(new View.OnTouchListener() {
private Handler handler;
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch(motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
if(handler != null) return true;
handler = new Handler();
handler.postDelayed(action,50);
break;
case MotionEvent.ACTION_UP:
if(handler == null) return true;
handler.removeCallbacks(action);
handler = null;
break;
}
return true;
}
Runnable action = new Runnable() {
@Override public void run() {
shipX = ship.getX() - 25;
ship.setX(shipX);
handler.postDelayed(this,50);
}
};
});
rightButton.setOnTouchListener(new View.OnTouchListener() {
private Handler handler;
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch(motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
if(handler != null) return true;
handler = new Handler();
handler.postDelayed(action,50);
break;
case MotionEvent.ACTION_UP:
if(handler == null) return true;
handler.removeCallbacks(action);
handler = null;
break;
}
return true;
}
Runnable action = new Runnable() {
@Override public void run() {
shipX = ship.getX() + 25;
ship.setX(shipX);
handler.postDelayed(this,50);
}
};
});
leftFireButton.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch(motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
//TODO FIRE BULLET....
leftFireButton.setBackgroundResource(R.drawable.red_button_pressed);
soundPool.play(soundID,1.0f,0.5f,1,0,1.0f);
return true;
case MotionEvent.ACTION_UP:
leftFireButton.setBackgroundResource(R.drawable.red_button);
//widgets.removeView(laser);
return true;
}
return false;
}
});
rightFireButton.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch(motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
//TODO FIRE BULLET
rightFireButton.setBackgroundResource(R.drawable.red_button_pressed);
soundPool.play(soundID,1.0f,0.5f,1,0,1.0f);
return true;
case MotionEvent.ACTION_UP:
rightFireButton.setBackgroundResource(R.drawable.red_button);
//widgets.removeView(laser);
return true;
}
return false;
}
});
//Setup ship
RelativeLayout.LayoutParams shipParams = new RelativeLayout.LayoutParams(250, 250);
//Setup a 200 x 200 ImageView for Left Button
RelativeLayout.LayoutParams leftBtn = new RelativeLayout.LayoutParams(200,200);
//Setup a 200 x 200 ImageView for Right Button
RelativeLayout.LayoutParams rightBtn = new RelativeLayout.LayoutParams(200,200);
//Setup a 200 x 200 ImageView for Left Fire Button
RelativeLayout.LayoutParams leftFireBtn = new RelativeLayout.LayoutParams(200,200);
//Setup a 200 x 200 ImageView for Right Fire Button
RelativeLayout.LayoutParams rightFireBtn = new RelativeLayout.LayoutParams(200,200);
//Add rules to align the left button programmatically
leftBtn.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
leftBtn.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
//Add rules to align the right button programmatically
rightBtn.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
rightBtn.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
//Add rules to align left and right fire buttons
leftFireBtn.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
rightFireBtn.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
leftFireBtn.addRule(RelativeLayout.ABOVE,leftButton.getId());
rightFireBtn.addRule(RelativeLayout.ABOVE, rightButton.getId());
//leftFireBtn.topMargin = 850;
//rightFireBtn.topMargin = 850;
shipParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
shipParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
//shipParams.bottomMargin = 100;
//Now set the params
leftButton.setLayoutParams(leftBtn);
rightButton.setLayoutParams(rightBtn);
leftFireButton.setLayoutParams(leftFireBtn);
rightFireButton.setLayoutParams(rightFireBtn);
ship.setLayoutParams(shipParams);
//Set the content view of the game
this.setContentView(game);
}
public void loadSounds(Context context) {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
soundPool = new SoundPool.Builder().setMaxStreams(10).build();
}
else {
soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 1);
}
soundID = soundPool.load(context,R.raw.laser,1);
}
@Override
protected void onPause() {
super.onPause();
mp.pause();
gameView.pause();
}
@Override
protected void onResume() {
super.onResume();
mp.start();
gameView.resume();
}
public class GameView extends SurfaceView implements Runnable {
Thread gameViewThread = null;
SurfaceHolder surfaceHolder;
boolean okToRun = true;
Bitmap star;
Bitmap three_pixel_star;
public GameView(Context context) {
super(context);
//initialize holder
surfaceHolder = this.getHolder();
}
@Override
public void run() {
while(okToRun) {
if(!surfaceHolder.getSurface().isValid()) {
continue;
}
Canvas gameCanvas = surfaceHolder.lockCanvas();
customOnDraw(gameCanvas);
surfaceHolder.unlockCanvasAndPost(gameCanvas);
}
}
protected void customOnDraw(Canvas canvas) {
Random random = new Random();
Random random1 = new Random();
canvas.drawColor(Color.BLACK);
star = BitmapFactory.decodeResource(getResources(), R.drawable.single_pixel_star);
three_pixel_star = BitmapFactory.decodeResource(getResources(),R.drawable.three_pixel_star);
canvas.drawBitmap(star, random1.nextInt(canvas.getWidth()-star.getWidth()),random1.nextInt(canvas.getHeight()-star.getHeight()), null);
canvas.drawBitmap(three_pixel_star, random.nextInt(canvas.getWidth()-three_pixel_star.getWidth()),random.nextInt(canvas.getHeight()-three_pixel_star.getHeight()), null);
}
public void pause() {
okToRun = false;
while(true) {
try {
gameViewThread.join();
} catch(InterruptedException e) {
Log.v("ERROR", e.getMessage());
}
break;
}
gameViewThread = null;
}
public void resume() {
okToRun = true;
gameViewThread = new Thread(this);
gameViewThread.start();
}
}
}