I've been trying to create a simple game where a Bitmap (called hunter) moves in the direction of a tap on the screen. I've been following along with this tutorial: https://www.youtube.com/watch?v=oLf32M6lUKo. It advised using a SurfaceView to draw the Bitmap and an OnTouchListener to help move the character.
Unfortunately, the emulator simply shows a black screen when I try to run the code.
Here's my code.
public class MoveTwo extends Activity implements View.OnTouchListener {
Bitmap hunter;
OurView v;
float x, y;
float newX, newY;
Paint p;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
v = new OurView(this);
v.setOnTouchListener(this);
hunter = BitmapFactory.decodeResource(getResources(), R.drawable.hunter);
x = y = 0;
setContentView(v);
this.p = new Paint();
p.setColor(Color.WHITE);
}
public boolean onTouch(View v, MotionEvent me) {
newX = me.getX();
newY = me.getY();
return true;
}
public class OurView extends SurfaceView implements Runnable {
Thread t = null;
boolean ok = false;
SurfaceHolder holder;
public OurView(Context context) {
super(context);
holder = getHolder();
}
public void run() {
while (ok == true) {
if (!holder.getSurface().isValid()) {
continue;
}
if (newY > y) {
y += 5;
}
if (newY < y) {
y -= 5;
}
if (newX > x) {
x +=5;
}
if (newX < x) {
x -= 5;
}
Canvas c = holder.lockCanvas();
c.drawARGB(255, 150, 150, 10);
c.drawBitmap(hunter, x, y, p);
holder.unlockCanvasAndPost(c);
}
}
public void pause() {
ok = false;
while (true) {
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
break;
}
t = null;
}
public void resume() {
ok = true;
t = new Thread(this);
t.start();
}
}
}
Do you have any recommendations for me? I'm unfamiliar with SurfaceView, so I've been having trouble trying to figure out the API and find a solution on my own.
Thanks!