Adding Sprites To A Pool To Be Used - java

Okay so i have ran into a small dilemma.
I have a Generic Pool that allows me to recycle and reuse my sprites. The issue is that i have 6 textures i would like to load into the pool to make sure each of them have a chance to be pulled out of the pool.
What is happening now is the same sprite is being recycled and used over and over. Here is my pool code.
public class ObjectPool extends GenericPool<Sprite> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private TextureRegion texture1;
private TextureRegion texture2;
private TextureRegion texture3;
private TextureRegion texture4;
private TextureRegion texture5;
private TextureRegion texture6;
private final Scene Gamescene;
private final VertexBufferObjectManager spriteVertexBuffer;
private Sprite fruit;
private final float CAMERA_WIDTH;
private final float CAMERA_HEIGHT;
public static boolean sprite_touched;
private final Camera camera;
// Variables
private final float minDuration = 3.1f;
private final float maxDuration = 5.1f;
private final TextureRegion blueParticleRegion;
private final Sound PersonTouchedSound;
private PointParticleEmitter particleEmitter;
private SpriteParticleSystem particleSystem;
private Random random = new Random();
// ===========================================================
// Constructors
// ===========================================================
public ObjectPool(final TextureRegion Region1,final TextureRegion Region2,final TextureRegion Region3,final TextureRegion Region4,final TextureRegion Region5, final TextureRegion Region6,
VertexBufferObjectManager spriteBufferObject, Camera camera,
Sound sound, Scene scene, TextureRegion particle) {
this.texture1 = Region1;
this.texture2 = Region2;
this.texture3 = Region3;
this.texture4 = Region4;
this.texture5 = Region5;
this.texture6 = Region6;
this.CAMERA_HEIGHT = camera.getHeight();
this.CAMERA_WIDTH = camera.getWidth();
this.camera = camera;
this.PersonTouchedSound = sound;
this.blueParticleRegion = particle;
Gamescene = scene;
initTrail(-70, -70);
this.spriteVertexBuffer = spriteBufferObject;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
#Override
protected Sprite onAllocatePoolItem() {
int sprite = random.nextInt(1)+6;
switch(sprite){
case 1:
fruit = new Sprite(210, -10, 60, 100, this.texture1,
this.spriteVertexBuffer) {
#Override
public boolean onAreaTouched(final TouchEvent pSceneTouchEvent,
final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
// Detects if player is outside of bounds
final float width = this.getWidth();
final float height = this.getHeight();
float x = pSceneTouchEvent.getX() - width / 2;
float y = pSceneTouchEvent.getY() - height / 2;
if (x < 0)
x = 0;
if (y < 0)
y = 0;
if (x > (CAMERA_WIDTH - width))
x = CAMERA_WIDTH - width;
if (y > (CAMERA_HEIGHT - height))
y = (CAMERA_HEIGHT - height);
moveTrail(x, this.getY());
if (pSceneTouchEvent.isActionDown()) {
this.setScale(2f);
sprite_touched = true;
PersonTouchedSound.play();
}
if (pSceneTouchEvent.isActionUp()) {
this.setScale(1f);
particleEmitter.setCenter(-70, -70);
sprite_touched = false;
}
this.setPosition(x, this.getY());
return true;
}
};
break;
case 2:
fruit = new Sprite(210, -10, 60, 100, this.texture2,
this.spriteVertexBuffer) {
#Override
public boolean onAreaTouched(final TouchEvent pSceneTouchEvent,
final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
// Detects if player is outside of bounds
final float width = this.getWidth();
final float height = this.getHeight();
float x = pSceneTouchEvent.getX() - width / 2;
float y = pSceneTouchEvent.getY() - height / 2;
if (x < 0)
x = 0;
if (y < 0)
y = 0;
if (x > (CAMERA_WIDTH - width))
x = CAMERA_WIDTH - width;
if (y > (CAMERA_HEIGHT - height))
y = (CAMERA_HEIGHT - height);
moveTrail(x, this.getY());
if (pSceneTouchEvent.isActionDown()) {
this.setScale(2f);
sprite_touched = true;
PersonTouchedSound.play();
}
if (pSceneTouchEvent.isActionUp()) {
this.setScale(1f);
particleEmitter.setCenter(-70, -70);
sprite_touched = false;
}
this.setPosition(x, this.getY());
return true;
}
};
break;
case 3:
fruit = new Sprite(210, -10, 60, 100, this.texture3,
this.spriteVertexBuffer) {
#Override
public boolean onAreaTouched(final TouchEvent pSceneTouchEvent,
final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
// Detects if player is outside of bounds
final float width = this.getWidth();
final float height = this.getHeight();
float x = pSceneTouchEvent.getX() - width / 2;
float y = pSceneTouchEvent.getY() - height / 2;
if (x < 0)
x = 0;
if (y < 0)
y = 0;
if (x > (CAMERA_WIDTH - width))
x = CAMERA_WIDTH - width;
if (y > (CAMERA_HEIGHT - height))
y = (CAMERA_HEIGHT - height);
moveTrail(x, this.getY());
if (pSceneTouchEvent.isActionDown()) {
this.setScale(2f);
sprite_touched = true;
PersonTouchedSound.play();
}
if (pSceneTouchEvent.isActionUp()) {
this.setScale(1f);
particleEmitter.setCenter(-70, -70);
sprite_touched = false;
}
this.setPosition(x, this.getY());
return true;
}
};
break;
case 4:
fruit = new Sprite(210, -10, 60, 100, this.texture4,
this.spriteVertexBuffer) {
#Override
public boolean onAreaTouched(final TouchEvent pSceneTouchEvent,
final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
// Detects if player is outside of bounds
final float width = this.getWidth();
final float height = this.getHeight();
float x = pSceneTouchEvent.getX() - width / 2;
float y = pSceneTouchEvent.getY() - height / 2;
if (x < 0)
x = 0;
if (y < 0)
y = 0;
if (x > (CAMERA_WIDTH - width))
x = CAMERA_WIDTH - width;
if (y > (CAMERA_HEIGHT - height))
y = (CAMERA_HEIGHT - height);
moveTrail(x, this.getY());
if (pSceneTouchEvent.isActionDown()) {
this.setScale(2f);
sprite_touched = true;
PersonTouchedSound.play();
}
if (pSceneTouchEvent.isActionUp()) {
this.setScale(1f);
particleEmitter.setCenter(-70, -70);
sprite_touched = false;
}
this.setPosition(x, this.getY());
return true;
}
};
break;
case 5:
fruit = new Sprite(210, -10, 60, 100, this.texture5,
this.spriteVertexBuffer) {
#Override
public boolean onAreaTouched(final TouchEvent pSceneTouchEvent,
final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
// Detects if player is outside of bounds
final float width = this.getWidth();
final float height = this.getHeight();
float x = pSceneTouchEvent.getX() - width / 2;
float y = pSceneTouchEvent.getY() - height / 2;
if (x < 0)
x = 0;
if (y < 0)
y = 0;
if (x > (CAMERA_WIDTH - width))
x = CAMERA_WIDTH - width;
if (y > (CAMERA_HEIGHT - height))
y = (CAMERA_HEIGHT - height);
moveTrail(x, this.getY());
if (pSceneTouchEvent.isActionDown()) {
this.setScale(2f);
sprite_touched = true;
PersonTouchedSound.play();
}
if (pSceneTouchEvent.isActionUp()) {
this.setScale(1f);
particleEmitter.setCenter(-70, -70);
sprite_touched = false;
}
this.setPosition(x, this.getY());
return true;
}
};
break;
case 6:
fruit = new Sprite(210, -10, 60, 100, this.texture6,
this.spriteVertexBuffer) {
#Override
public boolean onAreaTouched(final TouchEvent pSceneTouchEvent,
final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
// Detects if player is outside of bounds
final float width = this.getWidth();
final float height = this.getHeight();
float x = pSceneTouchEvent.getX() - width / 2;
float y = pSceneTouchEvent.getY() - height / 2;
if (x < 0)
x = 0;
if (y < 0)
y = 0;
if (x > (CAMERA_WIDTH - width))
x = CAMERA_WIDTH - width;
if (y > (CAMERA_HEIGHT - height))
y = (CAMERA_HEIGHT - height);
moveTrail(x, this.getY());
if (pSceneTouchEvent.isActionDown()) {
this.setScale(2f);
sprite_touched = true;
PersonTouchedSound.play();
}
if (pSceneTouchEvent.isActionUp()) {
this.setScale(1f);
particleEmitter.setCenter(-70, -70);
sprite_touched = false;
}
this.setPosition(x, this.getY());
return true;
}
};
break;
}
return fruit;
}
#Override
protected void onHandleObtainItem(final Sprite pItem) {
pItem.reset();
}
#Override
protected void onHandleRecycleItem(final Sprite pItem) {
pItem.setVisible(false);
pItem.setPosition(210, -5);
pItem.setIgnoreUpdate(true);
particleEmitter.setCenter(-70, -70);
pItem.clearEntityModifiers();
}
private void initTrail(float x, float y) {
this.particleEmitter = new PointParticleEmitter(x, y);
this.particleSystem = new SpriteParticleSystem(particleEmitter, 100, 100,
360, this.blueParticleRegion, spriteVertexBuffer);
particleSystem.addParticleInitializer(new AlphaParticleInitializer<Sprite>(
1));
particleSystem
.addParticleInitializer(new BlendFunctionParticleInitializer<Sprite>(
GLES20.GL_BLEND_COLOR, GLES20.GL_ONE));
particleSystem
.addParticleInitializer(new VelocityParticleInitializer<Sprite>(0));
particleSystem
.addParticleInitializer(new ExpireParticleInitializer<Sprite>(.6f));
particleSystem.addParticleModifier(new ScaleParticleModifier<Sprite>(0, 1,
1, 0));
Gamescene.attachChild(particleSystem);
}
public void moveTrail(float x, float y) {
particleEmitter.setCenter(x, y);
}
private void fillPool(){
}
}

You must create 6 pools instead of one or use TiledTextureRegion and switch to required tile on obtaining item.

Related

How I can retrieve information on a canvas

I want to do a "zoomable paint", I mean a paint that I can zoom/zoom out and pan/drag the canvas and then draw on it.
I have a problem that I can't solve: when I draw while the canvas is zoomed, I retrieve the X and Y coordinate and effectively drawing it on the canvas. But these coordinates are not correct because of the zoomed canvas.
I tried to correct these (multiply by (zoomHeigh/screenHeight)) but I can't find a way to retrieve where I must draw on the original/none-zoomed screen
This is my code :
public class PaintView extends View {
public static int BRUSH_SIZE = 20;
public static final int DEFAULT_COLOR = Color.BLACK;
public static final int DEFAULT_BG_COLOR = Color.WHITE;
private static final float TOUCH_TOLERANCE = 4;
private float mX, mY;
private SerializablePath mPath;
private Paint mPaint;
private ArrayList<FingerPath> paths = new ArrayList<>();
private ArrayList<FingerPath> tempPaths = new ArrayList<>();
private int currentColor;
private int backgroundColor = DEFAULT_BG_COLOR;
private int strokeWidth;
private boolean emboss;
private boolean blur;
private boolean eraser;
private MaskFilter mEmboss;
private MaskFilter mBlur;
private Bitmap mBitmap;
private Canvas mCanvas;
private Paint mBitmapPaint = new Paint(Paint.DITHER_FLAG);
public boolean zoomViewActivated = false;
//These two constants specify the minimum and maximum zoom
private static float MIN_ZOOM = 1f;
private static float MAX_ZOOM = 5f;
private float scaleFactor = 1.f;
private ScaleGestureDetector detector;
//These constants specify the mode that we're in
private static int NONE = 0;
private static int DRAG = 1;
private static int ZOOM = 2;
private int mode;
//These two variables keep track of the X and Y coordinate of the finger when it first
//touches the screen
private float startX = 0f;
private float startY = 0f;
//These two variables keep track of the amount we need to translate the canvas along the X
//and the Y coordinate
private float translateX = 0f;
private float translateY = 0f;
//These two variables keep track of the amount we translated the X and Y coordinates, the last time we
//panned.
private float previousTranslateX = 0f;
private float previousTranslateY = 0f;
int currentPositionX = 0;
int currentPositionY = 0;
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
#Override
public boolean onScale(ScaleGestureDetector detector) {
scaleFactor *= detector.getScaleFactor();
scaleFactor = Math.max(MIN_ZOOM, Math.min(scaleFactor, MAX_ZOOM));
return true;
}
}
public ArrayList<FingerPath> getDividedPaths(float i){
for(FingerPath p : this.paths){
Matrix scaleMatrix = new Matrix();
scaleMatrix.setScale(i, i);
p.path.transform(scaleMatrix);
}
return this.paths;
}
public ArrayList<FingerPath> getPaths() {
return paths;
}
public void dividePath(float i) {
for(FingerPath p : this.paths){
Matrix scaleMatrix = new Matrix();
scaleMatrix.setScale(i, i);
p.path.transform(scaleMatrix);
}
}
public void setPaths(ArrayList<FingerPath> paths){
this.paths = paths;
}
public void setStrokeWidth(int value){
strokeWidth = value;
}
public PaintView(Context context) {
this(context, null);
detector = new ScaleGestureDetector(getContext(), new ScaleListener());
}
public PaintView(Context context, AttributeSet attrs) {
super(context, attrs);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(DEFAULT_COLOR);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setXfermode(null);
mPaint.setAlpha(0xff);
mEmboss = new EmbossMaskFilter(new float[] {1, 1, 1}, 0.4f, 6, 3.5f);
mBlur = new BlurMaskFilter(5, BlurMaskFilter.Blur.NORMAL);
detector = new ScaleGestureDetector(getContext(), new ScaleListener());
}
public void init(DisplayMetrics metrics) {
int height = metrics.heightPixels;
int width = metrics.widthPixels;
mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
currentColor = DEFAULT_COLOR;
strokeWidth = BRUSH_SIZE;
}
public void normal() {
emboss = false;
blur = false;
eraser = false;
}
public void emboss() {
emboss = true;
blur = false;
eraser = false;
}
public void blur() {
emboss = false;
blur = true;
eraser = false;
}
public void eraser() {
eraser = true;
}
public void cancel(){
if(paths.size() != 0){
tempPaths.add(paths.get(paths.size()-1));
paths.remove(paths.size()-1);
invalidate();
}
}
public void redo(){
if(tempPaths.size() != 0){
paths.add(tempPaths.get(tempPaths.size()-1));
tempPaths.remove(tempPaths.size()-1);
invalidate();
}
}
public void clear() {
backgroundColor = DEFAULT_BG_COLOR;
paths.clear();
normal();
invalidate();
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.save();
//We're going to scale the X and Y coordinates by the same amount
canvas.scale(scaleFactor, scaleFactor);
//If translateX times -1 is lesser than zero, let's set it to zero. This takes care of the left bound
if((translateX * -1) < 0) {
translateX = 0;
}
//This is where we take care of the right bound. We compare translateX times -1 to (scaleFactor - 1) * displayWidth.
//If translateX is greater than that value, then we know that we've gone over the bound. So we set the value of
//translateX to (1 - scaleFactor) times the display width. Notice that the terms are interchanged; it's the same
//as doing -1 * (scaleFactor - 1) * displayWidth
else if((translateX * -1) > (scaleFactor - 1) * getWidth()) {
translateX = (1 - scaleFactor) * getWidth();
}
if(translateY * -1 < 0) {
translateY = 0;
}
//We do the exact same thing for the bottom bound, except in this case we use the height of the display
else if((translateY * -1) > (scaleFactor - 1) * getHeight()) {
translateY = (1 - scaleFactor) * getHeight();
}
//We need to divide by the scale factor here, otherwise we end up with excessive panning based on our zoom level
//because the translation amount also gets scaled according to how much we've zoomed into the canvas.
canvas.translate(translateX / scaleFactor, translateY / scaleFactor);
/* The rest of your canvas-drawing code */
mCanvas.drawColor(backgroundColor);
if(paths != null){
for (FingerPath fp : paths) {
mPaint.setColor(fp.color);
mPaint.setStrokeWidth(fp.strokeWidth);
mPaint.setMaskFilter(null);
if (fp.emboss)
mPaint.setMaskFilter(mEmboss);
else if (fp.blur)
mPaint.setMaskFilter(mBlur);
if(fp.eraser) {
mPaint.setColor(DEFAULT_BG_COLOR);
}
mCanvas.drawPath(fp.path, mPaint);
}
}
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
canvas.restore();
}
private void touchStart(float x, float y) {
mPath = new SerializablePath();
FingerPath fp = new FingerPath(currentColor, emboss, blur, eraser, strokeWidth, mPath);
paths.add(fp);
tempPaths = new ArrayList<>();
mPath.reset();
mPath.moveTo(x, y);
mX = x;
mY = y;
}
private void touchMove(float x, float y) {
float dx = Math.abs(x - mX);
float dy = Math.abs(y - mY);
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
mX = x;
mY = y;
}
}
private void touchUp() {
mPath.lineTo(mX, mY);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if(zoomViewActivated){
boolean dragged = false;
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
mode = DRAG;
//We assign the current X and Y coordinate of the finger to startX and startY minus the previously translated
//amount for each coordinates This works even when we are translating the first time because the initial
//values for these two variables is zero.
startX = event.getX() - previousTranslateX;
startY = event.getY() - previousTranslateY;
break;
case MotionEvent.ACTION_MOVE:
translateX = event.getX() - startX;
translateY = event.getY() - startY;
//We cannot use startX and startY directly because we have adjusted their values using the previous translation values.
//This is why we need to add those values to startX and startY so that we can get the actual coordinates of the finger.
double distance = Math.sqrt(Math.pow(event.getX() - (startX + previousTranslateX), 2) +
Math.pow(event.getY() - (startY + previousTranslateY), 2)
);
if(distance > 0) {
dragged = true;
}
break;
case MotionEvent.ACTION_POINTER_DOWN:
mode = ZOOM;
break;
case MotionEvent.ACTION_UP:
mode = NONE;
dragged = false;
//All fingers went up, so let's save the value of translateX and translateY into previousTranslateX and
//previousTranslate
previousTranslateX = translateX;
previousTranslateY = translateY;
currentPositionX += previousTranslateX;
currentPositionY += previousTranslateY;
break;
case MotionEvent.ACTION_POINTER_UP:
mode = DRAG;
//This is not strictly necessary; we save the value of translateX and translateY into previousTranslateX
//and previousTranslateY when the second finger goes up
previousTranslateX = translateX;
previousTranslateY = translateY;
break;
}
detector.onTouchEvent(event);
//We redraw the canvas only in the following cases:
//
// o The mode is ZOOM
// OR
// o The mode is DRAG and the scale factor is not equal to 1 (meaning we have zoomed) and dragged is
// set to true (meaning the finger has actually moved)
if ((mode == DRAG && scaleFactor != 1f && dragged) || mode == ZOOM) {
invalidate();
}
}else{
float x = event.getX()*(getHeight()/scaleFactor)/getHeight()+currentPositionX;
float y = event.getY()*(getWidth()/scaleFactor)/getWidth()+currentPositionY;
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN :
touchStart(x, y);
invalidate();
break;
case MotionEvent.ACTION_MOVE :
touchMove(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP :
touchUp();
invalidate();
break;
}
}
return true;
}
}

Save currentTime as long (AndroidStudio/libgdx

I am currently coding a game with Android Studio in the style of FlappyBird. I have two Cooldowns that give the user the possibility to use extra abilities.
In the main game view you can see 2 images that are grey and a timer under them. The timer goes from 10 to 0 and when zero is reached the number disappears, the image gets colored and the user knows he is able to activate the ability in the pause screen.
The problem:
When the game is starting the timer starts also and goes down as i wanted. But if the user enters the Pause Menu the Timer should stop and if he leaves it the Timer should run again.
I have a
long startTime = 0;
and a
long elapsedTime = (System.currentTimeMillis() - startTime) / 1000;
It all works but I cannot save the current time in a long and can't find any function for it!
I know the code is very long but the important part is in the drawWorld()-method in the if statement GameState.Running.
public class PlaneGame extends ApplicationAdapter{
private static final float PLANE_JUMP_IMPULSE = 350;
private static final float GRAVITY = -20;
private static final float PLANE_VELOCITY_X = 200;
private static final float PLANE_START_Y = 240;
private static final float PLANE_START_X = 50;
private static final int STATE_START = 0;
private static final int STATE_RUNNING = 1;
private static final int STATE_OVER = 2;
SpriteBatch batch;
OrthographicCamera camera;
OrthographicCamera uiCamera;
Texture background;
TextureRegion ground;
float groundOffsetX = 0;
TextureRegion ceiling;
TextureRegion rock;
TextureRegion rockDown;
TextureRegion planeSmall;
TextureRegion planeSmallBlack;
Animation plane;
TextureRegion ready;
TextureRegion gameOver;
TextureRegion pause;
BitmapFont font;
Vector2 planePosition = new Vector2();
Vector2 planeVelocity = new Vector2();
float planeStateTime = 0;
Vector2 gravity = new Vector2();
Array<Rock> rocks = new Array<Rock>();
GameState gameState = GameState.Start; /*neeeeeeewwwww*/
int score = 0;
long startTime = 0;
long startTime2;
long elapsedTime;
long savedTime;
boolean wantToSeeTime = true;
boolean wantToSeeTimePause = true;
float timeCdRock = 0;
float timeCdPlane = 0;
Rectangle rect1 = new Rectangle();
Rectangle rect2 = new Rectangle();
Music music;
Sound point;
Sound explode;
//this gets called repeatedly to run the game
#Override
public void render () {
//clear the screen so we can draw the next one
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
long saveTime = elapsedTime;
//update the position of the plane and rocks
updateWorld();
elapsedTime = saveTime;
//now draw the updated screen
drawWorld();
}
//initialize objects and load assets when game starts
#Override
public void create () {
startTime = TimeUtils.nanoTime(); /*Neeeewwwwwwwww !!!*/
Gdx.input.setInputProcessor(new GestureDetector(new MyGestureListener()));
batch = new SpriteBatch();
camera = new OrthographicCamera();
camera.setToOrtho(false, 800, 480);
uiCamera = new OrthographicCamera();
uiCamera.setToOrtho(false, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
uiCamera.update();
font = new BitmapFont(Gdx.files.internal("arial.fnt"));
background = new Texture("background.png");
ground = new TextureRegion(new Texture("ground.png"));
ceiling = new TextureRegion(ground);
ceiling.flip(true, true);
rock = new TextureRegion(new Texture("rock.png"));
rockDown = new TextureRegion(rock);
rockDown.flip(false, true);
Texture frame1 = new Texture("plane1.png");
frame1.setFilter(TextureFilter.Linear, TextureFilter.Linear);
Texture frame2 = new Texture("plane2.png");
Texture frame3 = new Texture("plane3.png");
planeSmall = new TextureRegion(new Texture("planeSmall.png"));
planeSmallBlack = new TextureRegion(new Texture("planeSmallBlack.png"));
ready = new TextureRegion(new Texture("ready.png"));
gameOver = new TextureRegion(new Texture("gameover.png"));
pause = new TextureRegion(new Texture("pause.png"));
plane = new Animation(0.05f, new TextureRegion(frame1), new TextureRegion(frame2), new TextureRegion(frame3), new TextureRegion(frame2));
plane.setPlayMode(PlayMode.LOOP);
music = Gdx.audio.newMusic(Gdx.files.internal("music.mp3"));
music.setLooping(true);
music.play();
point = Gdx.audio.newSound(Gdx.files.internal("point.ogg"));
explode = Gdx.audio.newSound(Gdx.files.internal("explode.wav"));
resetWorld();
}
//reset the state of the game
private void resetWorld() {
score = 0;
startTime = 0;
groundOffsetX = 0;
planePosition.set(PLANE_START_X, PLANE_START_Y);
planeVelocity.set(0, 0);
gravity.set(0, GRAVITY);
camera.position.x = 400;
//randomize the position and direction of the rocks
rocks.clear();
for(int i = 0; i < 5; i++) {
boolean isDown = MathUtils.randomBoolean();
rocks.add(new Rock(700 + i * 200, isDown?480-rock.getRegionHeight(): 0, isDown? rockDown: rock));
}
}
//use the time elapsed since the last call to render() to determine how much to update the game
private void updateWorld() {
float deltaTime = Gdx.graphics.getDeltaTime();
planeStateTime += deltaTime;
/*if(Gdx.input.justTouched()) {
if(gameState == STATE_START) {
gameState = STATE_RUNNING;
}
if(gameState == STATE_RUNNING) {
planeVelocity.set(PLANE_VELOCITY_X, PLANE_JUMP_IMPULSE);
}
if(gameState == STATE_OVER) {
gameState = STATE_START;
resetWorld();
}
}*/
if(gameState != GameState.Start) planeVelocity.add(gravity);
planePosition.mulAdd(planeVelocity, deltaTime);
camera.position.x = planePosition.x + 350;
if(camera.position.x - groundOffsetX > ground.getRegionWidth() + 400) {
groundOffsetX += ground.getRegionWidth();
}
rect1.set(planePosition.x + 20, planePosition.y, plane.getKeyFrames()[0].getRegionWidth() - 20, plane.getKeyFrames()[0].getRegionHeight());
for(Rock r: rocks) {
//if the rock is off the screen, give it a new location in front of the plane
if(camera.position.x - r.position.x > 400 + r.image.getRegionWidth()) {
boolean isDown = MathUtils.randomBoolean();
r.position.x += 5 * 200;
r.position.y = isDown?480-rock.getRegionHeight(): 0;
r.image = isDown? rockDown: rock;
r.counted = false;
}
rect2.set(r.position.x + (r.image.getRegionWidth() - 30) / 2 + 20, r.position.y, 20, r.image.getRegionHeight() - 10);
//check if the plane crashed
if(rect1.overlaps(rect2)) {
if(gameState != GameState.GameOver) explode.play();
gameState = GameState.GameOver;
planeVelocity.x = 0;
}
//award a point for not crashing into a rock
if(r.position.x < planePosition.x && !r.counted) {
score++;
r.counted = true;
point.play();
}
}
//check if the plane crashed
if(planePosition.y < ground.getRegionHeight() - 20 ||
planePosition.y + plane.getKeyFrames()[0].getRegionHeight() > 480 - ground.getRegionHeight() + 20) {
if(gameState != GameState.GameOver) explode.play();
gameState = GameState.GameOver;
planeVelocity.x = 0;
}
}
//draw the background, rocks, and plane to the screen and possibly some ui text
private void drawWorld() {
elapsedTime = (System.currentTimeMillis() - startTime) / 1000;
camera.update();
batch.setProjectionMatrix(camera.combined);
batch.begin();
batch.draw(background, camera.position.x - background.getWidth() / 2, 0);
for(Rock rock: rocks) {
batch.draw(rock.image, rock.position.x, rock.position.y);
}
batch.draw(ground, groundOffsetX, 0);
batch.draw(ground, groundOffsetX + ground.getRegionWidth(), 0);
batch.draw(ceiling, groundOffsetX, 480 - ceiling.getRegionHeight());
batch.draw(ceiling, groundOffsetX + ceiling.getRegionWidth(), 480 - ceiling.getRegionHeight());
batch.draw(plane.getKeyFrame(planeStateTime), planePosition.x, planePosition.y);
batch.end();
batch.setProjectionMatrix(uiCamera.combined);
batch.begin();
if(gameState == GameState.Start) {
batch.draw(ready, Gdx.graphics.getWidth() / 2 - ready.getRegionWidth() / 2, Gdx.graphics.getHeight() / 2 - ready.getRegionHeight() / 2);
}
if(gameState == GameState.GameOver) {
batch.draw(gameOver, Gdx.graphics.getWidth() / 2 - gameOver.getRegionWidth() / 2, Gdx.graphics.getHeight() / 2 - gameOver.getRegionHeight() / 2);
}
if(gameState == GameState.GameOver || gameState == GameState.Running) {
font.draw(batch, "" + score, Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() - 60);
}
if(gameState == GameState.Running || gameState == GameState.Pause) {
//font.draw(batch, "" + (10 - elapsedTime), (Gdx.graphics.getWidth() / 2) / 3, Gdx.graphics.getHeight() - 260);
if(wantToSeeTime){
font.draw(batch, "" + (5 - elapsedTime), (Gdx.graphics.getWidth() / 2) / 3, Gdx.graphics.getHeight() - 260);
}
if((5 -(elapsedTime) > 0)) {
batch.draw(planeSmallBlack, (Gdx.graphics.getWidth() / 2) / 3, Gdx.graphics.getHeight() - 250);
}else {
batch.draw(planeSmall, (Gdx.graphics.getWidth() / 2) / 3, Gdx.graphics.getHeight() - 250);
wantToSeeTime = false;
}
}
if(gameState == GameState.Pause){
batch.draw(pause, Gdx.graphics.getWidth() / 2 - pause.getRegionWidth() / 2, Gdx.graphics.getHeight() / 2 - pause.getRegionHeight() / 2);
if(wantToSeeTimePause){
font.draw(batch, "" + (savedTime), (Gdx.graphics.getWidth() / 2) / 3, Gdx.graphics.getHeight() - 260);
}
}
batch.end();
}
//object to hold all pertinent information for a rock
static class Rock {
Vector2 position = new Vector2();
TextureRegion image;
boolean counted;
public Rock(float x, float y, TextureRegion image) {
this.position.x = x;
this.position.y = y;
this.image = image;
}
}
// Neeeeeeeewwwww
static enum GameState {
Start, Running, GameOver, Pause
}
private class MyGestureListener implements GestureDetector.GestureListener {
#Override
public boolean touchDown(float x, float y, int pointer, int button) {
return false;
}
#Override
public boolean tap(float x, float y, int count, int button) {
if(gameState == GameState.Start) {
gameState = GameState.Running;
startTime = System.currentTimeMillis();
}
if(gameState == GameState.Running) {
planeVelocity.set(PLANE_VELOCITY_X, PLANE_JUMP_IMPULSE);
}
if(gameState == GameState.GameOver) {
gameState = GameState.Start;
resetWorld();
}
/*if((gameState == GameState.Pause) && (count == 2)) {
planeVelocity.set(PLANE_VELOCITY_X, PLANE_JUMP_IMPULSE);
gravity.set(0,GRAVITY);
gameState = GameState.Running;
}*/
return true;
}
#Override
public boolean longPress(float x, float y) {
return false;
}
#Override
public boolean fling(float velocityX, float velocityY, int button) {
if(gameState == GameState.Running) {
planePosition.set(planePosition.x, planePosition.y);
planeVelocity.set(0,0);
gravity.set(0, 0);
savedTime = System.currentTimeMillis() / 1000;
wantToSeeTime = false;
wantToSeeTimePause = true;
gameState = GameState.Pause;
} else {
planeVelocity.set(PLANE_VELOCITY_X, PLANE_JUMP_IMPULSE);
gravity.set(0,GRAVITY);
wantToSeeTime = true;
wantToSeeTimePause = false;
elapsedTime -= savedTime;
gameState = GameState.Running;
}
/*if(gameState == GameState.Pause) {
planeVelocity.set(PLANE_VELOCITY_X, PLANE_JUMP_IMPULSE);
gravity.set(0,GRAVITY);
gameState = GameState.Running;
}*/
return true;
}
#Override
public boolean pan(float x, float y, float deltaX, float deltaY) {
return false;
}
#Override
public boolean panStop(float x, float y, int pointer, int button) {
return false;
}
#Override
public boolean zoom(float initialDistance, float distance) {
return false;
}
#Override
public boolean pinch(Vector2 initialPointer1, Vector2 initialPointer2, Vector2 pointer1, Vector2 pointer2) {
return false;
}
public void pinchStop() {
}
}
}
Thanks for your help!
You can use joda time for advanced operations
Please check the link for your reference
http://www.joda.org/joda-time/userguide.html
I'm going to assume that your game runs as part of a loop. Ideally what you should have is a starting time when the ability is activated, which counts down during the cooldown based on how much time has elapsed since the last iteration of your loop. For example, for an ability with a 10 second cooldown:
final long abilityLength = 10 * 1000;
long cooldownRemaining = 0;
long lastTimestamp;
boolean isPaused = false;
private void doAbility() {
if (cooldownRemaining <= 0) {
cooldownRemaining = abilityLength;
}
}
public void main(int[] args) {
lastTimestamp = System.currentTimeMillis();
while(true) { // your main game loop
// Time (in ms) elapsed since the last iteration of this loop
long delta = System.currentTimeMillis() - lastTimestamp;
... // Other game code
if (cooldownRemaining > 0 && !isPaused) {
// Subtract the delta from the remaing cooldown time.
cooldownRemaining -= delta;
}
lastTimeStamp = System.currentTimeMillis();
}
}

Draw lines between points, each moving in random direction

I'm working on a Java Game using LWJGL. I made a particle system and would like to obtain same result as found on this website: http://play.cubedpixels.de
This is what I got so far:
I tried my best and the problem is it's stopping and they are only moving in one direction. Also the lines are not like on this website. On the website it's smoother and better. They are using OpenGL too.
How to solve these problems and make my implementation better, more like it is one the website?
The code below shows two classes: ParticleGalaxy and Particle. Latter one is inner class of the former, but for clarity I've split them into separate snippets.
ParticleGalaxy:
public class ParticleGalaxy
{
private int count;
private int width;
private int height;
private int mousex;
private int mousey;
public ArrayList<Particle> particles = new ArrayList();
private Random random = new Random();
private TimerUtil timer = new TimerUtil();
int state = 0;
int a = 255;
int r = 255;
int g = 0;
int b = 0;
public ParticleGalaxy(int count, int width, int height)
{
this.count = count;
this.width = width;
this.height = height;
for(int i = 0; i < count; i++)
{
this.particles.add(
new Particle(this.random.nextInt(width),
this.random.nextInt(height)));
}
}
public void drawParticles(int mousex, int mousey)
{
this.mousex = mousex;
this.mousey = mousey;
for(Particle p : this.particles)
{
if(p.reset)
{
p.resetPosSize();
p.reset = false;
}
int x = Math.abs(p.getX() - mousex);
int y = Math.abs(p.getY() - mousey);
if((x < 40 && x > -40) && (y<35 && y>-40))
{
p.setConnect(true);
}
else
{
p.setConnect(false);
}
p.draw();
}
}
}
Particle:
public class Particle
{
private int x;
private int y;
private int k;
private int movey;
private int movex;
private int starty;
private int startx;
private int locationy;
private int locationx;
private float size;
private boolean reset;
private boolean connect;
private Random random = new Random();
private TimerUtil timer = new TimerUtil();
private boolean moving = false;
private boolean start = false;
public Particle(int x, int y)
{
this.x = x;
this.y = y;
this.startx = x;
this.starty = y;
this.size = genRandom(0.57F, 0.71F);
}
public void setConnect(boolean bool)
{
connect = bool;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
private void drawLine(int xto, int yto, int xfrom, int yfrom)
{
GL11.glLineWidth(1.2f);
GL11.glColor3f(1.0f, 1.0f, 1.0f);
GL11.glBegin(GL11.GL_LINE_STRIP);
GL11.glVertex2d(xto, yto);
GL11.glVertex2d(xfrom, yfrom);
GL11.glEnd();
}
public void draw()
{
if(!start)
{
start = true;
movex = height - random.nextInt(height);
movey = width - random.nextInt(width);
move(startx, starty, movex, movey);
}
float speed = 1;
float elapsed = 0.01f;
// On starting movement
float distance = (float)Math.sqrt(Math.pow(movex - startx, 2) +
Math.pow(movey - starty, 2));
float directionX = (movex - startx) / distance;
float directionY = (movey - starty) / distance;
if(moving == true)
{
x += directionX * speed * elapsed;
y += directionY * speed * elapsed;
if(Math.sqrt(Math.pow(x - startx, 2) + Math.pow(y - starty, 2)) >= distance)
{
x = (int)movex;
y = (int)movey;
resetPosSize();
this.reset = true;
moving = false;
}
}
this.k += 1;
int xx = 0;
int yy = 0;
this.locationx = this.x + xx;
this.locationy = this.y + yy;
if(locationx < 0 || locationy < 0)
this.reset = true;
if(locationx > width || locationy > height)
this.reset = true;
GuiUtils.drawCircle(this.x + xx, this.y + yy, this.size, -1);
if(connect)
{
for(Particle p : particles)
{
if(p.connect)
drawLine(locationx, locationy, p.locationx, p.locationy);
}
}
}
public void move(int startX, int startY, int endX, int endY)
{
x = (int)startX;
y = (int)startY;
moving = true;
}
public void resetPosSize()
{
this.x = this.random.nextInt(ParticleGalaxy.this.width);
this.y = this.random.nextInt(ParticleGalaxy.this.height);
startx = x;
starty = y;
movex = height - random.nextInt(height);
movey = width - random.nextInt(width);
move(startx, starty, movex, movey);
}
public float genRandom(float min, float max)
{
return (float)(min + Math.random() * (max - min + 1.0F));
}
}

Rectangle -change width and height on motion event android?

I need to draw the rectangle from the center of the canvas based on ACTION_MOVE.
I tried this way
public class CustomRectangle extends View {
private Bitmap bitTopLeft;
private Bitmap bitTopRight;
private Bitmap bitBottomLeft;
private Bitmap bitBottomRight;
private Paint rectAnglePaint;
private Context context;
private Paint bitmapPaint;
private Rect rect;
private int maxX;
private int maxY;
private int centerX;
private int centerY;
private Paint canvasPaint;
public CustomRectangle(Context context) {
super(context);
this.context = context;
Init();
}
private void Init() {
bitTopLeft = BitmapFactory.decodeResource(context.getResources(),
R.drawable.squarsmall);
bitTopRight = BitmapFactory.decodeResource(context.getResources(),
R.drawable.squarsmall);
bitBottomLeft = BitmapFactory.decodeResource(context.getResources(),
R.drawable.squarsmall);
bitBottomRight = BitmapFactory.decodeResource(context.getResources(),
R.drawable.squarsmall);
rectAnglePaint = new Paint();
rectAnglePaint.setColor(Color.GREEN);
rectAnglePaint.setStrokeWidth(5);
rectAnglePaint.setStyle(Paint.Style.STROKE);
rectAnglePaint = new Paint();
rectAnglePaint.setColor(Color.GREEN);
rectAnglePaint.setStrokeWidth(5);
rectAnglePaint.setStyle(Paint.Style.STROKE);
bitmapPaint = new Paint();
bitmapPaint.setColor(Color.BLACK);
rect = new Rect();
Display display = ((Activity) context).getWindowManager()
.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
maxX = size.x;
maxY = size.y;
centerX = maxX / 2;
centerY = maxY / 2;
rect.left = centerX / 2 + bitBottomRight.getWidth() / 2;
rect.top = centerY / 2 + bitBottomRight.getWidth() / 2;
rect.right = centerX + centerX / 2 + bitBottomRight.getWidth() / 2;
rect.bottom = centerY + centerY / 2 + bitBottomRight.getWidth() / 2;
canvasPaint = new Paint();
canvasPaint.setColor(Color.TRANSPARENT);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawPaint(canvasPaint);
// Path p = new Path();
canvas.drawBitmap(bitTopLeft,
rect.left - bitBottomRight.getWidth() / 2, rect.top
- bitBottomRight.getWidth() / 2, bitmapPaint);
canvas.drawBitmap(bitTopRight, rect.right - bitBottomRight.getWidth()
/ 2, rect.top - bitBottomRight.getWidth() / 2, bitmapPaint);
canvas.drawBitmap(bitBottomLeft, rect.left - bitBottomRight.getWidth()
/ 2, rect.bottom - bitBottomRight.getWidth() / 2, bitmapPaint);
canvas.drawBitmap(bitBottomRight,
rect.right - bitBottomRight.getWidth() / 2, rect.bottom
- bitBottomRight.getWidth() / 2, bitmapPaint);
canvas.drawRect(rect, rectAnglePaint);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
invalidate();
break;
case MotionEvent.ACTION_MOVE:
int currentx = (int) event.getX();
int currenty = (int) event.getY();
Calculatingpoint(currentx, currenty);
break;
case MotionEvent.ACTION_UP:
break;
default:
break;
}
return true;
}
private void Calculatingpoint(int x, int y) {
if (x < maxX && y < maxY) {
int dx = 0;
int dy = 0;
dx = rect.right - x;
dy = rect.bottom - y;
// this is working perfect when i touched right bottom.
rect.inset(dx, dy);
invalidate();
}
}
}
But when i touch other corners the rectangle is gone.
I need to draw the rectangle from center point. i need to increase or decrease the width and height based on the touch.
Please advice, how to achieve this. Please give me samples.
I find the Direction from the user touching position, Here is my updated code.
public class CustomRectangle extends View {
private Bitmap bitTopLeft;
private Bitmap bitTopRight;
private Bitmap bitBottomLeft;
private Bitmap bitBottomRight;
private Paint rectAnglePaint;
private Context context;
private Paint bitmapPaint;
private Rect rect;
private int maxX;
private int maxY;
private int centerX;
private int centerY;
private Paint canvasPaint;
private String direction;
public CustomRectangle(Context context) {
super(context);
this.context = context;
Init();
}
private void Init() {
bitTopLeft = BitmapFactory.decodeResource(context.getResources(),
R.drawable.squarsmall);
bitTopRight = BitmapFactory.decodeResource(context.getResources(),
R.drawable.squarsmall);
bitBottomLeft = BitmapFactory.decodeResource(context.getResources(),
R.drawable.squarsmall);
bitBottomRight = BitmapFactory.decodeResource(context.getResources(),
R.drawable.squarsmall);
rectAnglePaint = new Paint();
rectAnglePaint.setColor(Color.GREEN);
rectAnglePaint.setStrokeWidth(5);
rectAnglePaint.setStyle(Paint.Style.STROKE);
rectAnglePaint = new Paint();
rectAnglePaint.setColor(Color.GREEN);
rectAnglePaint.setStrokeWidth(5);
rectAnglePaint.setStyle(Paint.Style.STROKE);
bitmapPaint = new Paint();
bitmapPaint.setColor(Color.BLACK);
rect = new Rect();
Display display = ((Activity) context).getWindowManager()
.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
maxX = size.x;
maxY = size.y;
centerX = maxX / 2;
centerY = maxY / 2;
rect.left = centerX / 2 + bitBottomRight.getWidth() / 2;
rect.top = centerY / 2 + bitBottomRight.getWidth() / 2;
rect.right = centerX + centerX / 2 + bitBottomRight.getWidth() / 2;
rect.bottom = centerY + centerY / 2 + bitBottomRight.getWidth() / 2;
canvasPaint = new Paint();
canvasPaint.setColor(Color.TRANSPARENT);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawPaint(canvasPaint);
// Path p = new Path();
canvas.drawBitmap(bitTopLeft,
rect.left - bitBottomRight.getWidth() / 2, rect.top
- bitBottomRight.getWidth() / 2, bitmapPaint);
canvas.drawBitmap(bitTopRight, rect.right - bitBottomRight.getWidth()
/ 2, rect.top - bitBottomRight.getWidth() / 2, bitmapPaint);
canvas.drawBitmap(bitBottomLeft, rect.left - bitBottomRight.getWidth()
/ 2, rect.bottom - bitBottomRight.getWidth() / 2, bitmapPaint);
canvas.drawBitmap(bitBottomRight,
rect.right - bitBottomRight.getWidth() / 2, rect.bottom
- bitBottomRight.getWidth() / 2, bitmapPaint);
canvas.drawRect(rect, rectAnglePaint);
}
float x1, x2, y1, y2, dx, dy;
#Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
x1 = event.getRawX();
y1 = event.getRawY();
invalidate();
break;
case MotionEvent.ACTION_MOVE:
x2 = event.getRawX();
y2 = event.getRawY();
int currentx = (int) event.getX();
int currenty = (int) event.getY();
Calculatingpoint(currentx, currenty);
break;
case MotionEvent.ACTION_UP:
break;
default:
break;
}
return true;
}
private void Calculatingpoint(int x, int y) {
if (x2 < maxX && y2 < maxY) {
int dx = 0;
int dy = 0;
// dx = rect.right - (int)x2 ;
// dy = (int)y2 - rect.top ;
//
// Log.e("dx", ""+dx);
// Log.e("dy", ""+dy);
boolean isLeft = false;
boolean isTop = false;
if (x2 > maxX / 2) {
direction = "right";
isLeft = false;
} else {
direction = "left";
isLeft = true;
}
if (y2 > maxY / 2) {
direction = "bottom";
isTop = false;
} else {
direction = "top";
isTop = true;
}
if (!isLeft && !isTop) {
dx = rect.right - (int) x2;
dy = rect.bottom - (int) y2;
}
if (isLeft && !isTop) {
dx = (int) x2 - rect.left;
dy = rect.bottom - (int) y2;
}
if (isLeft && isTop) {
dx = (int) x2 - rect.left;
dy = (int) y2 - rect.top;
}
if (!isLeft && isTop) {
dx = rect.right - (int) x2;
dy = (int) y2 - rect.top;
}
// this will perfect
rect.inset(dx, dy);
invalidate();
}
}
}

Eclipse, drawCircle function doesn't draw to the correct location

I made a program to draw a ball bouncing around the screen. It worked fine yesterday, but I just loaded it up and now it won't draw at the correct X location, its just stuck at 0. Y is still fine though..
class GameThreadView extends SurfaceView implements Runnable {
// for thread
Thread renderThread = null;
// volatile equals keep order of execution
volatile boolean running = false;
// for canvas, also used to synchronize
SurfaceHolder holder;
GameThreadAndroid gta;
Paint bg;
Paint fg;
// game stuff
int frameCount = 0;
int count = 0;
float aDeltaTime = 0f;
float accumTime = 0f;
int touchX = -50;
int touchY = -50;
float ballX, ballY = 0.5f;
float moveX, moveY = 0.2f;
Random r = new Random();
public GameThreadView(Context context) {
super(context);
gta = (GameThreadAndroid)context;
holder = getHolder();
fg = new Paint(Paint.ANTI_ALIAS_FLAG);
fg.setTextSize(36);
fg.setTextAlign(Paint.Align.CENTER);
fg.setColor(getResources().getColor(R.color.text));
bg = new Paint();
bg.setColor(getResources().getColor(R.color.background));
Log.d("GAME","GameThreadView");
//
moveY = r.nextFloat() * 0.5f;
}
/*
* Actually always starts a new thread
*/
public void resume() {
running = true;
renderThread = new Thread(this);
renderThread.start();
}
/*
* Actually kills thread
*/
public void pause() {
running = false;
while(true) {
try {
renderThread.join();
break;
} catch (InterruptedException e) {
// retry
}
}
renderThread = null;
}
public void run() {
long startTime = System.nanoTime();
while(running) {
if(!holder.getSurface().isValid())
continue;
float deltaTime = (System.nanoTime()-startTime)/1000000000.0f;
startTime = System.nanoTime();
updateGame(deltaTime);
Canvas canvas = holder.lockCanvas();
drawSurface(canvas);
holder.unlockCanvasAndPost(canvas);
}
}
// All game logic
private void updateGame(float deltaTime) {
accumTime += deltaTime;
count++;
if (accumTime > 1f) {
aDeltaTime = deltaTime;
frameCount = count;
count = 0;
accumTime = 0;
Log.d("GAME", String.format("frame count = %d", frameCount));
}
// move the ball
ballX += moveX * deltaTime;
ballY += moveY * deltaTime;
// hit walls
if(ballX > 1.0f){
ballX = 1.0f;
moveX = -moveX;
}
if(ballY > 1.0f){
ballY = 1.0f;
moveY = -moveY;
}
if(ballX < 0.0f){
ballX = 0.0f;
moveX = -moveX;
}
if(ballY < 0.0f){
ballY = 0.0f;
moveY = -moveY;
}
}
private void drawSurface(Canvas canvas) {
canvas.drawPaint(bg);
int w = canvas.getWidth() / 2;
canvas.drawText(Integer.toString(frameCount), w, canvas.getHeight() * 1/3, fg);
canvas.drawText(Float.toString(aDeltaTime), w, canvas.getHeight() * 2/3, fg);
canvas.drawCircle(ballX * canvas.getWidth(), ballY * canvas.getHeight(), 20, fg);
}
/*
* Called from outside this object so must be synchronized
* #see android.view.View#onTouchEvent(android.view.MotionEvent)
*/
public boolean onTouchEvent(MotionEvent event) {
synchronized (this) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
touchX = (int) event.getX();
touchY = (int) event.getY();
break;
}
return true;
}
}
I think the problem is that you never initialize moveX (its initialized with zero) in here:
float moveX, moveY = 0.2f;
and the, in the next method, you set moveY again, but moveX is still with the value of zero:
public GameThreadView(Context context) {
super(context);
gta = (GameThreadAndroid)context;
holder = getHolder();
fg = new Paint(Paint.ANTI_ALIAS_FLAG);
fg.setTextSize(36);
fg.setTextAlign(Paint.Align.CENTER);
fg.setColor(getResources().getColor(R.color.text));
bg = new Paint();
bg.setColor(getResources().getColor(R.color.background));
Log.d("GAME","GameThreadView");
// Here you set moveY
moveY = r.nextFloat() * 0.5f;
// You need to add somthing similar to moveX, like this
moveX = r.nextFloat() * 0.5f;
}
With that change it should run as expected.
Hope it helps you :)

Categories

Resources