Sprite drawing every few secs - java

i want to execute this code in the following code again and again in defined intervals
for (Sprite sprite : sprites) {
sprite.onDraw(canvas);
}
i tryed few methods but i am stuck with errors . because i have all my animation timed with sleep and thread extended class
package com.okok;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.SurfaceHolder.Callback;
public class GameView extends SurfaceView {
private Bitmap bmp;
private SurfaceHolder holder;
private GameLoopThread gameLoopThread;
private List<Sprite> sprites = new ArrayList<Sprite>();
private long lastClick;
private Bitmap bmpBlood;
private List<TempSprite> temps = new ArrayList<TempSprite>();
private int mint;
public GameView(Context context) {
super(context);
gameLoopThread = new GameLoopThread(this);
holder = getHolder();
holder.addCallback(new Callback() {
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
createSprites();
gameLoopThread.setRunning(true);
gameLoopThread.start();
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
}
});
bmpBlood = BitmapFactory.decodeResource(getResources(), R.drawable.blast);
}
private void createSprites() {
sprites.add(createSprite(R.drawable.greenenact));
sprites.add(createSprite(R.drawable.greenenact));
sprites.add(createSprite(R.drawable.greenenact));
}
private Sprite createSprite(int resouce) {
Bitmap bmp = BitmapFactory.decodeResource(getResources(), resouce);
return new Sprite(this, bmp);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.rgb(21, 181, 195));
for (int i = temps.size() - 1; i >= 0; i--) {
temps.get(i).onDraw(canvas);
}
for (Sprite sprite : sprites) {
sprite.onDraw(canvas);
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (System.currentTimeMillis() - lastClick > 500) {
lastClick = System.currentTimeMillis();
synchronized (getHolder()) {
float x = event.getX();
float y =event.getY();
for (int i = sprites.size() - 1; i >= 0; i--) {
Sprite sprite = sprites.get(i);
if (sprite.isCollition(x, y)) {
sprites.remove(sprite);
temps.add(new TempSprite(temps, this, x, y, bmpBlood));
break;
}
}
}
}
return true;
}
}
This is the GameLoopThread class i used to move things
package com.okok;
import android.graphics.Canvas;
public class GameLoopThread extends Thread {
static final long FPS = 10;
private GameView view;
private boolean running = false;
public GameLoopThread(GameView view) {
this.view = view;
}
public void setRunning(boolean run) {
running = run;
}
#Override
public void run() {
long ticksPS = 1000 / FPS;
long startTime;
long sleepTime;
while (running) {
Canvas c = null;
startTime = System.currentTimeMillis();
try {
c = view.getHolder().lockCanvas();
synchronized (view.getHolder()) {
view.onDraw(c);
}
} finally {
if (c != null) {
view.getHolder().unlockCanvasAndPost(c);
}
}
sleepTime = ticksPS - (System.currentTimeMillis() - startTime);
try {
if (sleepTime > 0)
sleep(sleepTime);
else
sleep(10);
} catch (Exception e) {}
}
}
}

Try something like:
private void createSprites() {
{
new Thread(new Runnable() {
public void run() {
for (int z =0; z<20; z++ ) // total of 20 sprites
try
{
Thread.sleep(5000); // new enemy every 5 seconds
sprites.add(createSprite(R.drawable.image));
z++;
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}).start();
}

Related

java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader couldn't find "liblivecamera.so.so"

I am working on camera application. When I debug the application, it crashes and says
java.lang.UnsatisfiedLinkError:
dalvik.system.PathClassLoader[DexPathList[[zip file
"/data/app/org.tensorflow.lite.examples.detection-kuQobL0-J_-5EsHI7x5ShQ==/base.apk"],nativeLibraryDirectories=[/data/app/org.tensorflow.lite.examples.detection-kuQobL0-J_-5EsHI7x5ShQ==/lib/arm64,
/data/app/org.tensorflow.lite.examples.detection-kuQobL0-J_-5EsHI7x5ShQ==/base.apk!/lib/arm64-v8a,
/system/lib64, /vendor/lib64]]] couldn't find "liblibcamera.so.so"
It is showing this error at this line of code:-
static {
System.loadLibrary("livecamera");
}
My complete cameraview.java code
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.hardware.Camera;
import android.hardware.Camera.Size;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class CameraView extends SurfaceView implements Camera.PreviewCallback, SurfaceHolder.Callback,
OCRThread.TextRegionsListener {
private final List<Rect> regions = new ArrayList<>();
private Camera mCamera;
private byte[] mVideoSource;
private Bitmap mBackBuffer;
private OCRThread ocrThread;
private Paint focusPaint;
private Rect focusRect;
private Paint paintText;
private float horizontalRectRation;
private float verticalRectRation;
static {
System.loadLibrary("livecamera");
}
public CameraView(final Context context) {
this(context, null);
}
public CameraView(final Context context, final AttributeSet attributes) {
super(context, attributes);
getHolder().addCallback(this);
setWillNotDraw(false);
focusPaint = new Paint();
focusPaint.setColor(0xeed7d7d7);
focusPaint.setStyle(Paint.Style.STROKE);
focusPaint.setStrokeWidth(2);
focusRect = new Rect(0, 0, 0, 0);
paintText = new Paint();
paintText.setColor(0xeeff0000);
paintText.setStyle(Paint.Style.STROKE);
paintText.setStrokeWidth(4);
ocrThread = new OCRThread(context);
horizontalRectRation = 1.0f;
verticalRectRation = 1.0f;
}
public void setShowTextBounds(final boolean show) {
regions.clear();
ocrThread.setRegionsListener(show ? this : null);
invalidate();
}
public void makeOCR(final OCRThread.TextRecognitionListener listener) {
ocrThread.setTextRecognitionListener(listener);
}
public native void decode(final Bitmap pTarget, final byte[] pSource);
#Override
protected void onDraw(final Canvas canvas) {
if (focusRect.width() > 0) {
canvas.drawRect(focusRect, focusPaint);
}
if (mCamera != null) {
mCamera.addCallbackBuffer(mVideoSource);
drawTextBounds(canvas);
}
}
private void drawTextBounds(final Canvas canvas) {
for (Rect region : regions) {
canvas.drawRect(region.left * horizontalRectRation, region.top * verticalRectRation,
region.right * horizontalRectRation, region.bottom * verticalRectRation, paintText);
}
}
#Override
public void onPreviewFrame(final byte[] bytes, final Camera camera) {
decode(mBackBuffer, bytes);
ocrThread.updateBitmap(mBackBuffer);
}
#Override
public void surfaceCreated(final SurfaceHolder surfaceHolder) {
try {
mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
mCamera.setDisplayOrientation(90);
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.setPreviewCallbackWithBuffer(this);
startOcrThread();
} catch (IOException eIOException) {
mCamera.release();
mCamera = null;
throw new IllegalStateException();
}
}
private void startOcrThread() {
ocrThread.start();
}
#Override
public void surfaceChanged(final SurfaceHolder surfaceHolder, final int format, final int width, final int height) {
mCamera.stopPreview();
Size lSize = findBestResolution();
updateTextRectsRatio(width, height, lSize);
PixelFormat lPixelFormat = new PixelFormat();
PixelFormat.getPixelFormatInfo(mCamera.getParameters()
.getPreviewFormat(), lPixelFormat);
int lSourceSize = lSize.width * lSize.height * lPixelFormat.bitsPerPixel / 8;
mVideoSource = new byte[lSourceSize];
mBackBuffer = Bitmap.createBitmap(lSize.width, lSize.height,
Bitmap.Config.ARGB_8888);
Camera.Parameters lParameters = mCamera.getParameters();
lParameters.setPreviewSize(lSize.width, lSize.height);
mCamera.setParameters(lParameters);
mCamera.addCallbackBuffer(mVideoSource);
mCamera.startPreview();
}
private Size findBestResolution() {
List<Size> lSizes = mCamera.getParameters().getSupportedPreviewSizes();
Size lSelectedSize = mCamera.new Size(0, 0);
for (Size lSize : lSizes) {
if ((lSize.width >= lSelectedSize.width) && (lSize.height >= lSelectedSize.height)) {
lSelectedSize = lSize;
}
}
if ((lSelectedSize.width == 0) || (lSelectedSize.height == 0)) {
lSelectedSize = lSizes.get(0);
}
return lSelectedSize;
}
private void updateTextRectsRatio(final int width, final int height, final Size cameraSize) {
verticalRectRation = ((float) height) / cameraSize.width;
horizontalRectRation = ((float) width) / cameraSize.height;
}
#Override
public void surfaceDestroyed(final SurfaceHolder surfaceHolder) {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
mVideoSource = null;
mBackBuffer = null;
stopOcrThread();
}
}
private void stopOcrThread() {
boolean retry = true;
ocrThread.cancel();
ocrThread.setRegionsListener(null);
while (retry) {
try {
ocrThread.join();
retry = false;
} catch (InterruptedException e) {
}
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
float x = event.getX();
float y = event.getY();
Rect touchRect = new Rect(
(int) (x - 100),
(int) (y - 100),
(int) (x + 100),
(int) (y + 100));
final Rect targetFocusRect = new Rect(
touchRect.left * 2000 / this.getWidth() - 1000,
touchRect.top * 2000 / this.getHeight() - 1000,
touchRect.right * 2000 / this.getWidth() - 1000,
touchRect.bottom * 2000 / this.getHeight() - 1000);
doTouchFocus(targetFocusRect);
focusRect = touchRect;
invalidate();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
focusRect = new Rect(0, 0, 0, 0);
invalidate();
}
}, 1000);
}
return false;
}
private void doTouchFocus(final Rect tfocusRect) {
try {
final List<Camera.Area> focusList = new ArrayList<Camera.Area>();
Camera.Area focusArea = new Camera.Area(tfocusRect, 1000);
focusList.add(focusArea);
Camera.Parameters para = mCamera.getParameters();
para.setFocusAreas(focusList);
para.setMeteringAreas(focusList);
mCamera.setParameters(para);
mCamera.autoFocus(myAutoFocusCallback);
} catch (Exception e) {
e.printStackTrace();
}
}
Camera.AutoFocusCallback myAutoFocusCallback = new Camera.AutoFocusCallback() {
#Override
public void onAutoFocus(boolean arg0, Camera arg1) {
if (arg0) {
mCamera.cancelAutoFocus();
}
}
};
/**
* {#inheritDoc}
*/
#Override
public void onTextRegionsRecognized(final List<Rect> textRegions) {
regions.clear();
regions.addAll(textRegions);
invalidate();
}
}
``
Your problem is the statement:
static {
System.loadLibrary("libcamera.so");
}
System.loadLibrary is a Java method for loading a library in a platform-independant way, which means you don't have to specify the platform specific filename of the library, but instead you need to use the library name so without lib at the beginning and .so at the end. Java will make it platform specific for Linux by adding both.
So you have to change it to
static {
System.loadLibrary("camera");
}
and it will work and load libcamera.so (if this library is included in your app).

Basic Android Studio surfaceView code only works for old devices

So i was trying to make a simple mobile game for a school project. I setted up a simple SurfaceView thing and builded it on my phone with Android 12 (Api 32), but it doesn't draw anything. It enters the draw function of the view, but i can't see an output. It only works on a old friend's tablet with Android 4.4.2.
MySurfaceView.java
package com.example.lyceumgame;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class MySurfaceView extends SurfaceView implements SurfaceHolder.Callback {
Bitmap image;
Paint paint;
float iX, iY, tX = 0, tY = 0;
float dx = 0, dy = 0;
Resources res;
MyThread myThread;
float ws, hs;
float iw, ih;
boolean isFirstDraw = true;
public MySurfaceView(Context context) {
super(context);
getHolder().addCallback(this);
res = getResources();
iX = 100;
iY = 100;
paint = new Paint();
paint.setColor(Color.YELLOW);
paint.setStrokeWidth(5);
setAlpha(0);
}
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
myThread = new MyThread(surfaceHolder, this);
myThread.setRunning(true);
myThread.start();
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
boolean retry = true;
myThread.setRunning(false);
while (retry) {
try {
myThread.join();
retry = false;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
#Override
public void draw(Canvas canvas) {
super.draw(canvas);
setAlpha(0);
if (isFirstDraw){
ws = canvas.getWidth();
hs = canvas.getHeight();
isFirstDraw = false;
}
canvas.drawRGB(0,255,0);
canvas.drawLine(iX, iY, tX, tY, paint);
if(tX != 0)
delta();
iX += dx;
iY += dy;
checkScreen();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
tX = event.getX();
tY = event.getY();
delta();
return true;
}
void delta(){
double ro = Math.sqrt(Math.pow(tX-iX, 2)+Math.pow(tY-iY, 2));
double k = 10;
dx = (float) (k * (tX - iX)/ro);
dy = (float) (k * (tY - iY)/ro);
}
private void checkScreen(){
if(iY + ih >= hs && iY <= 0)
dy = -dy;
if(iX + iw >= ws && iX <= 0)
dx = -dx;
}
}
MyThread.java
package com.example.lyceumgame;
import android.graphics.Canvas;
import android.view.SurfaceHolder;
public class MyThread extends Thread {
boolean isRunning = false;
SurfaceHolder surfaceHolder;
MySurfaceView mySurfaceView;
long prevTime, nowTime;
int FPS=60;
int c=1000;
int koeff=c/FPS;
public MyThread(SurfaceHolder holder, MySurfaceView surfaceView) {
surfaceHolder = holder;
mySurfaceView = surfaceView;
prevTime = System.currentTimeMillis();
}
#Override
public void run() {
Canvas canvas;
while (isRunning){
if(!surfaceHolder.getSurface().isValid())
continue;
canvas = null;
nowTime = System.currentTimeMillis();
long ellapsedTime = nowTime - prevTime;
if(ellapsedTime > koeff){
prevTime = nowTime;
canvas = surfaceHolder.lockCanvas(null);
synchronized (surfaceHolder){
mySurfaceView.draw(canvas);
}
if (canvas != null){
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
}
void setRunning(boolean f){
isRunning = f;
}
}
MainActivity.java
package com.example.lyceumgame;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new MySurfaceView(this));
}
}
My SDK was in different location and code like this worked fine. I tried invalidating caches and moving SDK to previous location. It didn't work.

Android nullPointerException error

I am unable to run my program. The app gets crashed. I am trying to make the image move on the screen by touchEvent.
java.lang.NullPointerException: Attempt to invoke virtual method 'int com.example.swapnil.new1.model.conmponents.Speed.getxDirection()' on a null object reference
at com.example.swapnil.new1.GamePanel.update(GamePanel.java:89)
at com.example.swapnil.new1.MainThread.run(MainThread.java:32)
I have added the Speed class which I think is responsible for this exception. Suggest any updates.
Speed class has the getxDirection method which is causing the exception.
package com.example.swapnil.new1.model.conmponents;
public class Speed {
public static final int DIRECTION_RIGHT = 1;
public static final int DIRECTION_LEFT = -1;
public static final int DIRECTION_UP = -1;
public static final int DIRECTION_DOWN = 1;
private float xv = 1; // speed in x
private float yv = 1; // speed in y
private int xDirection = DIRECTION_RIGHT;
private int yDirection = DIRECTION_DOWN;
public Speed() {
this.xv = 1;
this.yv = 1;
}
public Speed(float xv, float yv) {
this.xv = xv;
this.yv = yv;
}
public float getXv() {
return xv;
}
public void setXv(float xv) {
this.xv = xv;
}
public float getYv() {
return yv;
}
public void setYv(float yv) {
this.yv = yv;
}
public int getxDirection() {
return xDirection;
}
public void setxDirection(int xDirection) {
this.xDirection = xDirection;
}
public int getyDirection() {
return yDirection;
}
public void setyDirection(int yDirection) {
this.yDirection = yDirection;
}
public void toggleXDirection() {
xDirection = xDirection * -1;
}
public void toggleYDirection() {
yDirection = yDirection * -1;
}
}
The MainThread class:
package com.example.swapnil.new1;
import android.graphics.Canvas;
import android.util.Log;
import android.view.SurfaceHolder;
public class MainThread extends Thread {
private static final String TAG = MainThread.class.getSimpleName();
private boolean running;
private SurfaceHolder surfaceHolder;
private GamePanel gamePanel;
public MainThread(SurfaceHolder surfaceHolder , GamePanel gamePanel) {
super();
this.surfaceHolder = surfaceHolder;
this.gamePanel = gamePanel;
}
public void setRunning(boolean running) {
this.running = running;
}
#Override
public void run() {
Canvas canvas;
Log.d(TAG , "Starting game loop");
while(running) {
canvas = null;
try {
canvas = this.surfaceHolder.lockCanvas();
synchronized (surfaceHolder) {
this.gamePanel.render(canvas);
this.gamePanel.update();
}
} finally {
if(canvas != null) {
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
}
}
The GamePanel class:
import android.app.Activity;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import com.example.swapnil.new1.model.Droid;
import com.example.swapnil.new1.model.conmponents.Speed;
public class GamePanel extends SurfaceView implements
SurfaceHolder.Callback {
private static final String TAG = GamePanel.class.getSimpleName();
private MainThread thread;
private Droid droid;
public GamePanel(Context context) {
super(context);
getHolder().addCallback(this);
droid = new Droid(BitmapFactory.decodeResource(getResources(),R.drawable.droid_1),50,50);
thread = new MainThread(getHolder() , this);
setFocusable(true);
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
thread.setRunning(true);
thread.start();
}
#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.join();
retry = false;
}catch (InterruptedException e) {
}
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
droid.handleActionDown((int)event.getX(),(int)event.getY());
if (event.getY() > getHeight() - 50) {
thread.setRunning(false);
((Activity)getContext()).finish();
} else {
Log.d(TAG , "Coords : x = " + event.getX() + ",y = " + event.getY());
}
}
if (event.getAction() == MotionEvent.ACTION_MOVE) {
if (droid.isTouched()) {
droid.setX((int)event.getX());
droid.setY((int) event.getY());
}
}
if (event.getAction() == MotionEvent.ACTION_UP) {
if (droid.isTouched()) {
droid.setTouched(false);
}
}
return true;
}
// changed protected to public
protected void render(Canvas canvas) {
canvas.drawColor(Color.BLACK);
droid.draw(canvas);
}
public void update() {
// collision with right
if (droid.getSpeed().getxDirection() == Speed.DIRECTION_RIGHT &&
droid.getX() + droid.getBitmap().getWidth()/2 >= getWidth()) {
droid.getSpeed().toggleXDirection();
}
//collision with left
if (droid.getSpeed().getxDirection() == Speed.DIRECTION_LEFT &&
droid.getX() - droid.getBitmap().getWidth()/2 <= 0) {
droid.getSpeed().toggleXDirection();
}
// collision with down
if (droid.getSpeed().getyDirection() == Speed.DIRECTION_DOWN &&
droid.getY() + droid.getBitmap().getHeight()/2 >= getHeight()) {
droid.getSpeed().toggleYDirection();
}
//collision with up
if (droid.getSpeed().getyDirection() == Speed.DIRECTION_UP &&
droid.getY() - droid.getBitmap().getHeight()/2 <= 0) {
droid.getSpeed().toggleYDirection();
}
droid.update();
}
}
Speed field in your Droid object is not set. In your GamePanel.update() method you are invoking getxDirection on this field and that cause NullPointerException.

Background moves farther and faster than anything else

OK, So Im drawing a bitmap beneath everything else for my background. Whenever the player moves it moves the enemy array 1 px and its supposed to do the same for the background. But whenever I move the background goes way faster and farther than everything else in the game. Can anyone tell me whats causing this? Heres the code. The code that moves everything is at the bottom in the set direction method.
package com.gametest;
import java.util.concurrent.CopyOnWriteArrayList;
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.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
public class GameSurfaceView extends Activity implements OnTouchListener {
double ran;
int touchX, touchY, screenWidth, screenHeight, objX, objY;
static int bgx, bgy, bgW, bgH, enemyCount, score, playerHealth;
static boolean canUpdate;
static MyView v;
static Bitmap orb, orb2, explosion, bg;
static CopyOnWriteArrayList<Sprite> copy = new CopyOnWriteArrayList<Sprite>();
static String hpString;
static Player player;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
v = new MyView(this);
v.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent me) {
switch (me.getAction()) {
case MotionEvent.ACTION_DOWN:
return true;
case MotionEvent.ACTION_MOVE:
return true;
case MotionEvent.ACTION_UP:
touchX = (int) me.getX();
touchY = (int) me.getY();
for (Sprite sprite : copy) {
sprite.checkTouch(touchX, touchY);
return true;
}
}
return true;
}
});
canUpdate = true;
screenWidth = v.getWidth();
screenHeight = v.getHeight();
playerHealth = 250;
hpString = "Health " + playerHealth;
ran = 0;
score = 0;
orb = BitmapFactory.decodeResource(getResources(), R.drawable.blue_orb);
orb2 = BitmapFactory.decodeResource(getResources(), R.drawable.red_orb);
bg = BitmapFactory.decodeResource(getResources(), R.drawable.bg1);
bgx = bg.getHeight()/2;
bgy = bg.getHeight()/2;
bgH = bg.getHeight();
bgW = bg.getWidth();
explosion = BitmapFactory.decodeResource(getResources(), R.drawable.explosion);
player = new Player(v, orb2, explosion, screenWidth, screenHeight);
createEnemies();
setContentView(v);
}
private void createEnemies() {
if (enemyCount < 5) {
screenWidth = v.getWidth();
screenHeight = v.getHeight();
copy.add(new Sprite(v, orb, explosion, screenWidth, screenHeight, copy.size()));
enemyCount++;
}
}
public static void checkECount(int id) {
canUpdate = false;
copy.remove(id);
enemyCount--;
CopyOnWriteArrayList<Sprite> c = new CopyOnWriteArrayList<Sprite>();
int index = 0;
for (Sprite s : copy) {
s.ID = index;
c.add(s);
index++;
}
score = score + 10;
copy = c;
canUpdate = true;
}
#Override
protected void onPause() {
super.onPause();
v.pause();
}
#Override
protected void onResume() {
super.onResume();
v.resume();
}
public class MyView extends SurfaceView implements Runnable {
Thread t = null;
SurfaceHolder holder;
boolean isItOk = false;
public MyView(Context context) {
super(context);
holder = getHolder();
}
#Override
public void run() {
while (isItOk == true) {
if (!holder.getSurface().isValid()) {
continue;
}
Canvas c = holder.lockCanvas();
if (canUpdate) {
canvas_draw(c);
}
holder.unlockCanvasAndPost(c);
try {
t.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
protected void canvas_draw(Canvas canvas) {
canvas.drawColor(Color.BLACK);
Rect bgRec = new Rect(bgx, bgy, bgx+bgW, bgy+bgH);
canvas.drawBitmap(bg, null, bgRec, null);
ran = Math.random() * 5;
if (ran > 4.5) {
createEnemies();
}
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setTextSize(15);
canvas.drawText(hpString, 10, 25, paint);
for (Sprite sprite : copy) {
sprite.sprite_draw(canvas);
}
Player.sprite_draw(canvas, copy);
}
public void pause() {
isItOk = false;
while (true) {
try {
t.join();
} catch (InterruptedException e) {
}
break;
}
t = null;
}
public void resume() {
isItOk = true;
t = new Thread(this);
t.start();
}
}
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
return false;
}
public static void damagePlayer() {
hpString = "Health " + playerHealth;
playerHealth = playerHealth - 5;
if (playerHealth < 0) {
hpString = "game over";
}
}
public static void setDirection(int i, int j) {
if (i == 0 && j == -1) {
for (Sprite s : copy) {
s.y++;
bgy++;
}
}
if (i == 0 && j == 1) {
for (Sprite s : copy) {
s.y--;
bgy--;
}
}
if (i == -1 && j == 0) {
for (Sprite s : copy) {
s.x++;
bgx++;
}
}
if (i == 1 && j == 0) {
for (Sprite s : copy) {
s.x--;
bgx--;
}
}
}
}
You are changing bgx based on the number of sprites you have in your copy Iterable. in your setDirection method, please move the bgy, bgx outside of the enhanced for loops, like in:
if (i == 0 && j == -1) {
for (Sprite s : copy) {
s.y++;
}
bgy++;
}

Canvas not drawing Android

I have been trying to start a new project and when I went to start up I couldn't get anything working. I have looked at the code for the past few hours and played with it but I can't remember how I fixed this last time it happened.
package org.waldev.canvascollisiontest;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.view.Menu;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class CollisionTest extends Activity {
private Panel game;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
game = new Panel(this);
setContentView(game);
}
public class Panel extends SurfaceView implements SurfaceHolder.Callback{
Threads thread;
public Panel(Context context) {
super(context);
thread = new Threads(this.getHolder(), this);
setFocusable(true);
}
public void onDraw(Canvas c)
{
c.drawColor(Color.BLUE);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
//when the game starts, run the thread\
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
holder.setFormat(PixelFormat.RGB_565);
thread.setRunning(true);
thread.start();
}
//if its destroyed, then destroy the thread
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
boolean retry = true;
thread.setRunning(false);
while (retry) {
try {
thread.join();
// bitmaps.recycleAll();
retry = false;
} catch (InterruptedException e) {
// we will try it again and again...
}
}
}
}
}
And the thread:
package org.waldev.canvascollisiontest;
import org.waldev.canvascollisiontest.CollisionTest.Panel;
import android.graphics.Canvas;
import android.view.SurfaceHolder;
public class Threads extends Thread{
SurfaceHolder surfaceHolder;
private Panel game;
private Canvas c;
private boolean isRunning = true;
// desired fps
private final static int MAX_FPS = 24;
// maximum number of frames to be skipped
private final static int MAX_FRAME_SKIPS = 0;
// the frame period
private final static int FRAME_PERIOD = 1000 / MAX_FPS;
public Threads(SurfaceHolder surfaceHolder, Panel panel){
this.surfaceHolder = surfaceHolder;
game = panel;
}
public void setRunning(boolean run){
isRunning = run;
}
public boolean getRunning(){
return isRunning();
}
public SurfaceHolder getSurface(){
return surfaceHolder;
}
#Override
public void run() {
Canvas canvas;
long beginTime; // the time when the cycle begun
long timeDiff; // the time it took for the cycle to execute
int sleepTime; // ms to sleep (<0 if we're behind)
int framesSkipped; // number of frames being skipped
boolean updated = false;
sleepTime = 0;
while (isRunning) {
canvas = null;
try {
canvas = this.surfaceHolder.lockCanvas();
synchronized (surfaceHolder) {
beginTime = System.currentTimeMillis();
framesSkipped = 0;
if(canvas != null)
{
game.onDraw(canvas);
}
timeDiff = System.currentTimeMillis() - beginTime;
sleepTime = (int)(FRAME_PERIOD - timeDiff);
if (sleepTime > 0) {
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {}
}
else
{
updated = false;
}
}
} finally {
// in case of an exception the surface is not left in
// an inconsistent state
if (canvas != null) {
surfaceHolder.unlockCanvasAndPost(canvas);
}
} // end finally
}
}
public boolean isRunning() {
return isRunning;
}
}
I threw some break points in there and it is never calling surfaceCreated in CollisionTest. I know it has to be something stupid that I am missing here, so if you see it let me know. Thanks!
William
I got it working, I forgot to add the:
getHolder().addCallback(this);
to the Constructor for Panel, which is what was causing it to not work. Thanks!

Categories

Resources