Bounce ball back android - java

I have take Example of Accelerator with SensorManager, in which canvas(ball) are get update its position as per device Accelerator are rotated. Here is image :
As shown in the image there is a ball and one line. The ball's position is frequently updated, while the line's position is static.
I would like to have the ball bounce back when it touches the line. I have tried since from 3 day, but don't understand how I can do this.
here is my code:
public class ballsensor extends Activity implements SensorEventListener {
// sensor-related
private SensorManager mSensorManager;
private Sensor mAccelerometer;
// animated view
private ShapeView mShapeView;
// screen size
private int mWidthScreen;
private int mHeightScreen;
// motion parameters
private final float FACTOR_FRICTION = 0.5f; // imaginary friction on the
// screen
private final float GRAVITY = 9.8f; // acceleration of gravity
private float mAx; // acceleration along x axis
private float mAy; // acceleration along y axis
private final float mDeltaT = 0.5f; // imaginary time interval between each
// acceleration updates
// timer
private Timer mTimer;
private Handler mHandler;
private boolean isTimerStarted = false;
private long mStart;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set the screen always portait
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// initializing sensors
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mAccelerometer = mSensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
// obtain screen width and height
Display display = ((WindowManager) this
.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
mWidthScreen = display.getWidth();
mHeightScreen = display.getHeight() - 35;
// initializing the view that renders the ball
mShapeView = new ShapeView(this);
mShapeView.setOvalCenter((int) (mWidthScreen * 0.6),
(int) (mHeightScreen * 0.6));
setContentView(mShapeView);
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
public void onSensorChanged(SensorEvent event) {
// obtain the three accelerations from sensors
mAx = event.values[0];
mAy = event.values[1];
float mAz = event.values[2];
// taking into account the frictions
mAx = Math.signum(mAx) * Math.abs(mAx)
* (1 - FACTOR_FRICTION * Math.abs(mAz) / GRAVITY);
mAy = Math.signum(mAy) * Math.abs(mAy)
* (1 - FACTOR_FRICTION * Math.abs(mAz) / GRAVITY);
}
#Override
protected void onResume() {
super.onResume();
// start sensor sensing
mSensorManager.registerListener(this, mAccelerometer,
SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onPause() {
super.onPause();
// stop senser sensing
mSensorManager.unregisterListener(this);
}
// the view that renders the ball
private class ShapeView extends SurfaceView implements
SurfaceHolder.Callback {
private final int RADIUS = 30;
private final float FACTOR_BOUNCEBACK = 0.50f;
private int mXCenter;
private int mYCenter;
private RectF mRectF;
private final Paint mPaint;
private ShapeThread mThread;
private float mVx;
private float mVy;
public ShapeView(Context context) {
super(context);
getHolder().addCallback(this);
mThread = new ShapeThread(getHolder(), this);
setFocusable(true);
mPaint = new Paint();
mPaint.setColor(0xFFFFFFFF);
mPaint.setAlpha(192);
mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
mPaint.setAntiAlias(true);
mRectF = new RectF();
}
// set the position of the ball
public boolean setOvalCenter(int x, int y) {
mXCenter = x;
mYCenter = y;
return true;
}
// calculate and update the ball's position
public boolean updateOvalCenter() {
mVx -= mAx * mDeltaT;
mVy += mAy * mDeltaT;
System.out.println("mVx is ::" + mVx);
System.out.println("mVy is ::" + mVy);
mXCenter += (int) (mDeltaT * (mVx + 0.6 * mAx * mDeltaT));
mYCenter += (int) (mDeltaT * (mVy + 0.6 * mAy * mDeltaT));
if (mXCenter < RADIUS) {
mXCenter = RADIUS;
mVx = -mVx * FACTOR_BOUNCEBACK;
}
if (mYCenter < RADIUS) {
mYCenter = RADIUS;
mVy = -mVy * FACTOR_BOUNCEBACK;
}
if (mXCenter > mWidthScreen - RADIUS) {
mXCenter = mWidthScreen - RADIUS;
mVx = -mVx * FACTOR_BOUNCEBACK;
}
if (mYCenter > mHeightScreen - 2 * RADIUS) {
mYCenter = mHeightScreen - 2 * RADIUS;
mVy = -mVy * FACTOR_BOUNCEBACK;
}
return true;
}
// update the canvas.
#Override
protected void onDraw(Canvas canvas) {
if (mRectF != null) {
mRectF.set(mXCenter - RADIUS, mYCenter - RADIUS, mXCenter
+ RADIUS, mYCenter + RADIUS);
canvas.drawColor(0XFF000000);
// canvas.drawOval(mRectF, mPaint);
Bitmap kangoo = BitmapFactory.decodeResource(getResources(),
R.drawable.stripe1);
Bitmap ball = BitmapFactory.decodeResource(getResources(),
R.drawable.blackwhiteball);
canvas.drawBitmap(ball, mXCenter - RADIUS, mYCenter - RADIUS,
mPaint);
canvas.drawBitmap(kangoo, 130, 10, null);
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
mThread.setRunning(true);
mThread.start();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
mThread.setRunning(false);
while (retry) {
try {
mThread.join();
retry = false;
} catch (InterruptedException e) {
}
}
}
}
class ShapeThread extends Thread {
private SurfaceHolder mSurfaceHolder;
private ShapeView mShapeView;
private boolean mRun = false;
public ShapeThread(SurfaceHolder surfaceHolder, ShapeView shapeView) {
mSurfaceHolder = surfaceHolder;
mShapeView = shapeView;
}
public void setRunning(boolean run) {
mRun = run;
}
public SurfaceHolder getSurfaceHolder() {
return mSurfaceHolder;
}
#Override
public void run() {
Canvas c;
while (mRun) {
mShapeView.updateOvalCenter();
c = null;
try {
c = mSurfaceHolder.lockCanvas(null);
synchronized (mSurfaceHolder) {
mShapeView.onDraw(c);
}
} finally {
if (c != null) {
mSurfaceHolder.unlockCanvasAndPost(c);
}
}
}
}
}
}

Rather than try to fix your code, work at the design level by developing a software architecture that has two components: physics model and display. The key is to separate the physics of the problem from the display. Modelling the physics becomes much easier when done separately from the display. Likewise the display also becomes easier. Have two separate packages - one for the physics and one for the display.
Start with a simpler version of the problem where the physics world just has a point and a line. Model the point reflecting off the line. You have some code that does this. Just rip it out of the current code. Make sure the physics does what you expect it to without worrying about the display.
Design a class for the ball. The ball has velocity and position properties. It has a move method that updates the position based on the velocity for one time click. The move method checks to see if it has interacted (collided) with the wall and changes the velocity according the physics you want your world to have. The collision detection is done by asking the wall were it is. The physics could be angle of incidence equals angle of reflection, or you could have a spin property on the ball that changes how the ball bounces. The key is that all of the physics modelling is done separately from the display. Similarly, you create a class for the wall. Initially the wall is fixed, but you could add movement to it. The nice thing is that if you've designed the ball class correctly changing the wall to make it move doesn't effect the design of the ball class. Also, none of these changes to the physics effect how the display is done.
Make a display that simply translates the physics into a presentation on the screen.
From there you can add complexity to your model. Make the point a circle. Redo the physics to make it work with this new complexity. The display won't change much, but keep them separate.
I have my CS1 class do versions of this same problem. Two years ago, I had them make a pong game. Last year a version of Centipede. This coming semester they'll have Breakout as a project. When they model the physics separately from the display, they get it working. When they don't, it is usually a muddled mess.

Physics modyle shall run in separate thread, and use best available time resolution for position updates. ( milliseconds should be enough ) This is how I design gameloop:
lastFrameTime = System.currentTimeMillis();
// as long as we run we move
while (state == GameState.RUNNING) {
currentFrame++;
timeNow = System.currentTimeMillis();
// sleep until this frame is scheduled
long l = lastFrameTime + FRAME_DELAY - timeNow;
updatePositions();
redraw();
if (l > 0L) {
try {
Thread.sleep(l);
}
catch (Exception exception) {
}
} else {
// something long kept us from updating, reset delays
lastFrameTime = timeNow;
l = FRAME_DELAY;
}
lastFrameTime = timeNow + l;
// be polite, let others play
Thread.yield();
}
It is important to give up control of the thread, for UI tasks which will be processing events and hive commands to your phyiscs engine.
As for collision detection - it is pretty simple math. Your line is vertical, and zou must just check whether difference in x-coord of line and center is got less than radius - then reverse x-componen of velocity

You can use Rect.intersects(Rect, Rect) to detect collisions. Use your bitmap width and height to set up the new Rects.
Here is a dirty example:
import java.util.Timer;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.Display;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.WindowManager;
public class ballsensor extends Activity implements SensorEventListener {
// sensor-related
private SensorManager mSensorManager;
private Sensor mAccelerometer;
// animated view
private ShapeView mShapeView;
// screen size
private int mWidthScreen;
private int mHeightScreen;
// motion parameters
private final float FACTOR_FRICTION = 0.5f; // imaginary friction on the
// screen
private final float GRAVITY = 9.8f; // acceleration of gravity
private float mAx; // acceleration along x axis
private float mAy; // acceleration along y axis
private final float mDeltaT = 0.5f; // imaginary time interval between each
// acceleration updates
// timer
private Timer mTimer;
private Handler mHandler;
private final boolean isTimerStarted = false;
private long mStart;
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set the screen always portait
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// initializing sensors
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mAccelerometer = mSensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
// obtain screen width and height
final Display display = ((WindowManager) this
.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
mWidthScreen = display.getWidth();
mHeightScreen = display.getHeight() - 35;
// initializing the view that renders the ball
mShapeView = new ShapeView(this);
mShapeView.setOvalCenter((int) (mWidthScreen * 0.6),
(int) (mHeightScreen * 0.6));
setContentView(mShapeView);
}
#Override
public void onAccuracyChanged(final Sensor sensor, final int accuracy) {
}
#Override
public void onSensorChanged(final SensorEvent event) {
// obtain the three accelerations from sensors
mAx = event.values[0];
mAy = event.values[1];
final float mAz = event.values[2];
// taking into account the frictions
mAx = Math.signum(mAx) * Math.abs(mAx)
* (1 - FACTOR_FRICTION * Math.abs(mAz) / GRAVITY);
mAy = Math.signum(mAy) * Math.abs(mAy)
* (1 - FACTOR_FRICTION * Math.abs(mAz) / GRAVITY);
}
#Override
protected void onResume() {
super.onResume();
// start sensor sensing
mSensorManager.registerListener(this, mAccelerometer,
SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onPause() {
super.onPause();
// stop senser sensing
mSensorManager.unregisterListener(this);
}
// the view that renders the ball
private class ShapeView extends SurfaceView implements
SurfaceHolder.Callback {
private final int RADIUS = 30;
private final float FACTOR_BOUNCEBACK = 0.50f;
private int mXCenter;
private int mYCenter;
private final RectF mRectF;
private final Paint mPaint;
private final ShapeThread mThread;
private float mVx;
private float mVy;
private final Rect lineRect = new Rect();
private final Rect ballRect = new Rect();
public ShapeView(final Context context) {
super(context);
getHolder().addCallback(this);
mThread = new ShapeThread(getHolder(), this);
setFocusable(true);
mPaint = new Paint();
mPaint.setColor(0xFFFFFFFF);
mPaint.setAlpha(192);
mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
mPaint.setAntiAlias(true);
mRectF = new RectF();
}
// set the position of the ball
public boolean setOvalCenter(final int x, final int y) {
mXCenter = x;
mYCenter = y;
return true;
}
// calculate and update the ball's position
public boolean updateOvalCenter() {
mVx -= mAx * mDeltaT;
mVy += mAy * mDeltaT;
System.out.println("mVx is ::" + mVx);
System.out.println("mVy is ::" + mVy);
mXCenter += (int) (mDeltaT * (mVx + 0.6 * mAx * mDeltaT));
mYCenter += (int) (mDeltaT * (mVy + 0.6 * mAy * mDeltaT));
if (mXCenter < RADIUS) {
mXCenter = RADIUS;
mVx = -mVx * FACTOR_BOUNCEBACK;
}
if (mYCenter < RADIUS) {
mYCenter = RADIUS;
mVy = -mVy * FACTOR_BOUNCEBACK;
}
if (mXCenter > mWidthScreen - RADIUS) {
mXCenter = mWidthScreen - RADIUS;
mVx = -mVx * FACTOR_BOUNCEBACK;
}
if (mYCenter > mHeightScreen - 2 * RADIUS) {
mYCenter = mHeightScreen - 2 * RADIUS;
mVy = -mVy * FACTOR_BOUNCEBACK;
}
if(Rect.intersects(lineRect, ballRect)){
mVx = -mVx * FACTOR_BOUNCEBACK;
mVy = -mVy * FACTOR_BOUNCEBACK;
mXCenter += (int) (mDeltaT * (mVx + 0.6 * mAx * mDeltaT)) * 5;
mYCenter += (int) (mDeltaT * (mVy + 0.6 * mAy * mDeltaT)) * 5;
}
return true;
}
// update the canvas.
#Override
protected void onDraw(final Canvas canvas) {
if (mRectF != null) {
mRectF.set(mXCenter - RADIUS, mYCenter - RADIUS, mXCenter
+ RADIUS, mYCenter + RADIUS);
canvas.drawColor(0XFF000000);
// canvas.drawOval(mRectF, mPaint);
final Bitmap kangoo = BitmapFactory.decodeResource(getResources(),
R.drawable.blankcard);
lineRect.set(130, 10, 130 + kangoo.getWidth(), 10 + kangoo.getHeight());
final Bitmap ball = BitmapFactory.decodeResource(getResources(),
R.drawable.blankcard);
ballRect.set(mXCenter - RADIUS, mYCenter - RADIUS, mXCenter - RADIUS + ball.getWidth(), mYCenter - RADIUS + ball.getHeight());
canvas.drawBitmap(ball, mXCenter - RADIUS, mYCenter - RADIUS,
mPaint);
canvas.drawBitmap(kangoo, 130, 10, null);
}
}
#Override
public void surfaceChanged(final SurfaceHolder holder, final int format, final int width,
final int height) {
}
#Override
public void surfaceCreated(final SurfaceHolder holder) {
mThread.setRunning(true);
mThread.start();
}
#Override
public void surfaceDestroyed(final SurfaceHolder holder) {
boolean retry = true;
mThread.setRunning(false);
while (retry) {
try {
mThread.join();
retry = false;
} catch (final InterruptedException e) {
}
}
}
}
class ShapeThread extends Thread {
private final SurfaceHolder mSurfaceHolder;
private final ShapeView mShapeView;
private boolean mRun = false;
public ShapeThread(final SurfaceHolder surfaceHolder, final ShapeView shapeView) {
mSurfaceHolder = surfaceHolder;
mShapeView = shapeView;
}
public void setRunning(final boolean run) {
mRun = run;
}
public SurfaceHolder getSurfaceHolder() {
return mSurfaceHolder;
}
#Override
public void run() {
Canvas c;
while (mRun) {
mShapeView.updateOvalCenter();
c = null;
try {
c = mSurfaceHolder.lockCanvas(null);
synchronized (mSurfaceHolder) {
mShapeView.onDraw(c);
}
} finally {
if (c != null) {
mSurfaceHolder.unlockCanvasAndPost(c);
}
}
}
}
}
}
Needs improvement but might get you on the right track.

Related

Not able to populate a custom view ( totally java based ) in a line layout ( Xml based )

I have a custom view which is totally Java based ( no XML ) code is below and i want to add this inside a new XML based layout ..Please guide how to do this however i also want that when it get displayed the screen will show 50 % xml layout and 50 % customview is it even possible ? please see below picture for more clarity
follows is the Java code of the animation :
public class AccelerometerPlayActivity extends Activity {
private SimulationView mSimulationView;
private SensorManager mSensorManager;
private PowerManager mPowerManager;
private WindowManager mWindowManager;
private Display mDisplay;
private WakeLock mWakeLock;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get an instance of the SensorManager
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
// Get an instance of the PowerManager
mPowerManager = (PowerManager) getSystemService(POWER_SERVICE);
// Get an instance of the WindowManager
mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
mDisplay = mWindowManager.getDefaultDisplay();
// Create a bright wake lock
mWakeLock = mPowerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, getClass()
.getName());
// instantiate our simulation view and set it as the activity's content
mSimulationView = new SimulationView(this);
mSimulationView.setBackgroundResource(R.drawable.wood);
setContentView(mSimulationView);
}
#Override
protected void onResume() {
super.onResume();
/*
* when the activity is resumed, we acquire a wake-lock so that the
* screen stays on, since the user will likely not be fiddling with the
* screen or buttons.
*/
mWakeLock.acquire();
// Start the simulation
mSimulationView.startSimulation();
mSimulationView.setLayoutParams(new FrameLayout.LayoutParams(700, 300));
}
#Override
protected void onPause() {
super.onPause();
/*
* When the activity is paused, we make sure to stop the simulation,
* release our sensor resources and wake locks
*/
// Stop the simulation
mSimulationView.stopSimulation();
// and release our wake-lock
mWakeLock.release();
}
class SimulationView extends LinearLayout implements SensorEventListener {
// diameter of the balls in meters
private static final float sBallDiameter = 0.004f;
private static final float sBallDiameter2 = sBallDiameter * sBallDiameter;
private final int mDstWidth;
private final int mDstHeight;
private Sensor mAccelerometer;
private long mLastT;
private float mXDpi;
private float mYDpi;
private float mMetersToPixelsX;
private float mMetersToPixelsY;
private float mXOrigin;
private float mYOrigin;
private float mSensorX;
private float mSensorY;
private float mHorizontalBound;
private float mVerticalBound;
private final ParticleSystem mParticleSystem;
/*
* Each of our particle holds its previous and current position, its
* acceleration. for added realism each particle has its own friction
* coefficient.
*/
class Particle extends View {
private float mPosX = (float) Math.random();
private float mPosY = (float) Math.random();
private float mVelX;
private float mVelY;
public Particle(Context context) {
super(context);
}
public Particle(Context context, AttributeSet attrs) {
super(context, attrs);
}
public Particle(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
public Particle(Context context, AttributeSet attrs, int defStyleAttr,
int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
public void computePhysics(float sx, float sy, float dT) {
final float ax = -sx/5;
final float ay = -sy/5;
mPosX += mVelX * dT + ax * dT * dT / 2;
mPosY += mVelY * dT + ay * dT * dT / 2;
mVelX += ax * dT;
mVelY += ay * dT;
}
/*
* Resolving constraints and collisions with the Verlet integrator
* can be very simple, we simply need to move a colliding or
* constrained particle in such way that the constraint is
* satisfied.
*/
public void resolveCollisionWithBounds() {
final float xmax = mHorizontalBound;
final float ymax = mVerticalBound;
final float x = mPosX;
final float y = mPosY;
if (x > xmax) {
mPosX = xmax;
mVelX = 0;
} else if (x < -xmax) {
mPosX = -xmax;
mVelX = 0;
}
if (y > ymax) {
mPosY = ymax;
mVelY = 0;
} else if (y < -ymax) {
mPosY = -ymax;
mVelY = 0;
}
}
}
/*
* A particle system is just a collection of particles
*/
class ParticleSystem {
static final int NUM_PARTICLES = 5;
private Particle mBalls[] = new Particle[NUM_PARTICLES];
ParticleSystem() {
/*
* Initially our particles have no speed or acceleration
*/
for (int i = 0; i < mBalls.length; i++) {
mBalls[i] = new Particle(getContext());
mBalls[i].setBackgroundResource(R.drawable.ball);
mBalls[i].setLayerType(LAYER_TYPE_HARDWARE, null);
addView(mBalls[i], new ViewGroup.LayoutParams(mDstWidth, mDstHeight));
}
}
/*
* Update the position of each particle in the system using the
* Verlet integrator.
*/
private void updatePositions(float sx, float sy, long timestamp) {
final long t = timestamp;
if (mLastT != 0) {
final float dT = (float) (t - mLastT) / 1000.f /** (1.0f / 1000000000.0f)*/;
final int count = mBalls.length;
for (int i = 0; i < count; i++) {
Particle ball = mBalls[i];
ball.computePhysics(sx, sy, dT);
}
}
mLastT = t;
}
/*
* Performs one iteration of the simulation. First updating the
* position of all the particles and resolving the constraints and
* collisions.
*/
public void update(float sx, float sy, long now) {
// update the system's positions
updatePositions(sx, sy, now);
// We do no more than a limited number of iterations
final int NUM_MAX_ITERATIONS = 1;
/*
* Resolve collisions, each particle is tested against every
* other particle for collision. If a collision is detected the
* particle is moved away using a virtual spring of infinite
* stiffness.
*/
boolean more = true;
final int count = mBalls.length;
for (int k = 0; k < NUM_MAX_ITERATIONS && more; k++) {
more = false;
for (int i = 0; i < count; i++) {
Particle curr = mBalls[i];
for (int j = i + 1; j < count; j++) {
Particle ball = mBalls[j];
float dx = ball.mPosX - curr.mPosX;
float dy = ball.mPosY - curr.mPosY;
float dd = dx * dx + dy * dy;
// Check for collisions
if (dd <= sBallDiameter2) {
/*
* add a little bit of entropy, after nothing is
* perfect in the universe.
*/
dx += ((float) Math.random() - 0.5f) * 0.0001f;
dy += ((float) Math.random() - 0.5f) * 0.0001f;
dd = dx * dx + dy * dy;
// simulate the spring
final float d = (float) Math.sqrt(dd);
final float c = (0.5f * (sBallDiameter - d)) / d;
final float effectX = dx * c;
final float effectY = dy * c;
curr.mPosX -= effectX;
curr.mPosY -= effectY;
ball.mPosX += effectX;
ball.mPosY += effectY;
more = true;
}
}
curr.resolveCollisionWithBounds();
}
}
}
public int getParticleCount() {
return mBalls.length;
}
public float getPosX(int i) {
return mBalls[i].mPosX;
}
public float getPosY(int i) {
return mBalls[i].mPosY;
}
}
public void startSimulation() {
/*
* It is not necessary to get accelerometer events at a very high
* rate, by using a slower rate (SENSOR_DELAY_UI), we get an
* automatic low-pass filter, which "extracts" the gravity component
* of the acceleration. As an added benefit, we use less power and
* CPU resources.
*/
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_GAME);
}
public void stopSimulation() {
mSensorManager.unregisterListener(this);
}
public SimulationView(Context context) {
super(context);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
mXDpi = metrics.xdpi;
mYDpi = metrics.ydpi;
mMetersToPixelsX = mXDpi / 0.0254f;
mMetersToPixelsY = mYDpi / 0.0254f;
// rescale the ball so it's about 0.5 cm on screen
mDstWidth = (int) (sBallDiameter * mMetersToPixelsX + 0.5f);
mDstHeight = (int) (sBallDiameter * mMetersToPixelsY + 0.5f);
mParticleSystem = new ParticleSystem();
Options opts = new Options();
opts.inDither = true;
opts.inPreferredConfig = Bitmap.Config.RGB_565;
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
// compute the origin of the screen relative to the origin of
// the bitmap
mXOrigin = (w - mDstWidth) * 0.5f; //#nyy this is changing the rect of balls to simulate
mYOrigin = (h - mDstHeight) * 0.5f;
mHorizontalBound = ((w / mMetersToPixelsX - sBallDiameter) * 0.5f);//#nyy this is changing the rect of balls to simulate
mVerticalBound = ((h / mMetersToPixelsY - sBallDiameter) * 0.5f);
}
#Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER)
return;
/*
* record the accelerometer data, the event's timestamp as well as
* the current time. The latter is needed so we can calculate the
* "present" time during rendering. In this application, we need to
* take into account how the screen is rotated with respect to the
* sensors (which always return data in a coordinate space aligned
* to with the screen in its native orientation).
*/
switch (mDisplay.getRotation()) {
case Surface.ROTATION_0:
mSensorX = event.values[0];
mSensorY = event.values[1];
break;
case Surface.ROTATION_90:
mSensorX = -event.values[1];
mSensorY = event.values[0];
break;
case Surface.ROTATION_180:
mSensorX = -event.values[0];
mSensorY = -event.values[1];
break;
case Surface.ROTATION_270:
mSensorX = event.values[1];
mSensorY = -event.values[0];
break;
}
}
#Override
protected void onDraw(Canvas canvas) {
/*
* Compute the new position of our object, based on accelerometer
* data and present time.
*/
final ParticleSystem particleSystem = mParticleSystem;
final long now = System.currentTimeMillis();
final float sx = mSensorX;
final float sy = mSensorY;
particleSystem.update(sx, sy, now);
final float xc = mXOrigin;
final float yc = mYOrigin;
final float xs = mMetersToPixelsX;
final float ys = mMetersToPixelsY;
final int count = particleSystem.getParticleCount();
for (int i = 0; i < count; i++) {
/*
* We transform the canvas so that the coordinate system matches
* the sensors coordinate system with the origin in the center
* of the screen and the unit is the meter.
*/
final float x = xc + particleSystem.getPosX(i) * xs;
final float y = yc - particleSystem.getPosY(i) * ys;
particleSystem.mBalls[i].setTranslationX(x);
particleSystem.mBalls[i].setTranslationY(y);
}
// and make sure to redraw asap
invalidate();
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
}
you are just setting setContentView(mSimulationView) to mSimulationView only.
you have include all content that is custom layout and linearlayout in xml file.
setContentView(R.layout.your_xml)
If i understood you correctly then you don't need to override the linearLayout your simulation view would look like this.
class SimulationView extends View implements SensorEventListener, ParticleSystemListener {
private final ParticleSystem mParticleSystem;
/* all your normal initialization */
public SimulationView(Context context) {
super(context);
/* all your normal initialization */
mParticleSystem = new mParticleSystem(this); // initialize the system here whatever resources you need for your particles if you use bitmaps you can pass a bitmap here
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
// we notify the particleSystem that the size has changed so i can adjust it's bounds
mParticleSystem.setBounds(left, top, right, bottom);
}
#Override
public void onSensorChanged(SensorEvent event) {
/* all your normal code */
mParticleSystem.updatePositions(x, y, time)
}
#Override
public void needNewFrame(){
invalidate();
}
#Override
protected void onDraw(Canvas canvas) {
/* draw your background or just call super witch will draw it for you */
mParticleSystem.drawAllParticles(canvas);
}
}
Create an interface to to get notified when we particle system wants to draw a new frame or simply pass the view and call invalidate on it;
interface ParticleSystemListener {
public void needNewFrame();
}
Your particleSystem should do all the computation and handle adding and removing particles as well as passing the dway command down to the particles.
class ParticleSystem {
private float mParticleSystemListener;
private Particle mBalls[] = new Particle[NUM_PARTICLES];
private Rect mBounds = new Rect();
public ParticleSystem (ParticleSystemListener listener) {
mParticleSystemListener = listener;
/* all your normal initialization */
}
// our particle system keeps track of the bounds in which it draws the particles and tells the particles when it has changed
public void setBounds(left, top, right, bottom){
mBounds.left = left;
mBounds.top = top;
mBounds.right = right;
mBounds.bottom = bottom;
for(ball : mBalls){
ball.boundsChanged();
}
// after we computed new positions is time to refresh the view
mParticleSystemListener.needNewFrame();
}
private void updatePositions(float sx, float sy, long timestamp){
/* all your normal computation*/
for(ball : mBalls){
ball.computePhysics(sx, sy, dT);
}
// after we computed new positions is time to refresh the view
mParticleSystemListener.needNewFrame();
}
// the view wants us to draw on this canvas so we just pass the canvas to the particles
public void drawAllParticles(canvas){
for(ball : mBalls){
ball.draw(canvas);
}
}
}
All the state is gonna reside in the particle class. the particle class should know its position and how to draw itself
class Particle {
private Paint mPaint;
private Bitmap mSprite;
private Rect mBounds;
public Particle(Rect bounds) {
mBounds = bounds;
/* initialize your paint here or get a bitmap passed in */
}
public void computePhysics(float sx, float sy, float dT);
public void boundsChanged(){
// move your particle since the bounds have changed
}
public void onDraw(Canvas canvas) {
canvas.drawCircle(x, y ,r, paint); // draw a circle at position
or
canvas.drawBitmap(mSprite, float left, float top, some paint or null) // draw a sprite
}
}
As you can see this is not the full implementation i didn't check if you calculate the accelerations and positions correctly this is just un overview of how your classes should look and never create objects inside your onDraw() loop. Inside onDraw() should live only code that is necessary for drawing. Handle All your calculations outside onDraw and when ready for a new frame call invalidate(). Or if you need even more performance you can override SurfaceView or TextureView.
Ok FInally i figured it out it was a very very simple solution however it took me 4 days of continuous googling and sample code reading trying to make sense of similar kind of apps
i got the idea from Adam Porter code for sensors and finally got this
Objective was to show the above attached Java ( dynamic view code ) where NO xml was ever involved however i want to run that code via XML by setting so that i can limit it in a small frame or layout instead of whole screen
follows are the steps i did
in XML file
1, create an XML file named :dyn under layouts
2, added a frame layout in that XML file with ID : fl ( framelayout)
and in my java file :
1, set the content to R.layout.dyn instead of previously set as msimulationview
2, created a java framelayout called jfl and then linked it with xml based framelayout called fl
3, added the view( msimulation view ) to the java based framelayout i.e. Jfl
follows is the code it just took 3 lines to achieve that ...
thanks for every one who took their time helping out this
follows is the code :
setContentView( R.layout.dyn);
FrameLayout jfl = findViewById( R.id.fl );
mSimulationView.setId( R.id.fl );
jfl.getContext();
jfl.addView( mSimulationView );
THanks a lot every one.
here is the complete Java file :
package com.example.sensormanager;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.BitmapFactory.Options;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.Surface;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import java.util.zip.Inflater;
public class acceleromparticles extends Activity {
public SimulationView mSimulationView;
private SensorManager mSensorManager;
private PowerManager mPowerManager;
private WindowManager mWindowManager;
private Display mDisplay;
private WakeLock mWakeLock;
public int ui = 1 ;
public FrameLayout fl;
/** Called when the activity is first created. */
#SuppressLint("ResourceType")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get an instance of the SensorManager
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
// Get an instance of the PowerManager
mPowerManager = (PowerManager) getSystemService(POWER_SERVICE);
// Get an instance of the WindowManager
mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
mDisplay = mWindowManager.getDefaultDisplay();
mSimulationView = new SimulationView(getApplicationContext());
// fl.addView( mSimulationView );
setContentView( R.layout.dyn);
FrameLayout jfl = findViewById( R.id.fl );
jfl.addView( mSimulationView );
mSimulationView.setBackgroundResource(R.drawable.wood);
// setContentView(mSimulationView);
}
#Override
protected void onResume() {
super.onResume();
/*
* when the activity is resumed, we acquire a wake-lock so that the
* screen stays on, since the user will likely not be fiddling with the
* screen or buttons.
*/
//mWakeLock.acquire();
// Start the simulation
mSimulationView.startSimulation();
// mSimulationView.setLayoutParams(new FrameLayout.LayoutParams(700, 300));
}
#Override
protected void onPause() {
super.onPause();
/*
* When the activity is paused, we make sure to stop the simulation,
* release our sensor resources and wake locks
*/
// Stop the simulation
mSimulationView.stopSimulation();
// and release our wake-lock
// mWakeLock.release();
}
class SimulationView extends FrameLayout implements SensorEventListener {
// diameter of the balls in meters
private static final float sBallDiameter = 0.0005f;
private static final float sBallDiameter2 = sBallDiameter * sBallDiameter;
private final int mDstWidth;
private final int mDstHeight;
private Sensor mAccelerometer;
private long mLastT;
private float mXDpi;
private float mYDpi;
private float mMetersToPixelsX;
private float mMetersToPixelsY;
private float mXOrigin;
private float mYOrigin;
private float mSensorX;
private float mSensorY;
private float mHorizontalBound;
private float mVerticalBound;
public final ParticleSystem mParticleSystem;
/*
* Each of our particle holds its previous and current position, its
* acceleration. for added realism each particle has its own friction
* coefficient.
*/
class Particle extends View {
private float mPosX = (float) Math.random();
private float mPosY = (float) Math.random();
private float mVelX;
private float mVelY;
public Particle(Context context) {
super( context );
}
public Particle(Context context, AttributeSet attrs) {
super(context, attrs);
}
public Particle(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public Particle(Context context, AttributeSet attrs, int defStyleAttr,
int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
public void computePhysics(float sx, float sy, float dT) {
final float ax = -sx/35; //viscosity changes
final float ay = -sy/35;
mPosX += mVelX * dT + ax * dT * dT ; //original /2
mPosY += mVelY * dT + ay * dT * dT ;
mVelX += ax * dT;
mVelY += ay * dT;
}
public void resolveCollisionWithBounds() {
final float xmax = mHorizontalBound;
final float ymax = mVerticalBound;
final float x = mPosX;
final float y = mPosY;
if (x > xmax) {
mPosX = xmax;
mVelX = 0;
} else if (x < -xmax) {
mPosX = -xmax;
mVelX = 0;
}
if (y > ymax) {
mPosY = ymax;
mVelY = 0;
} else if (y < -ymax) {
mPosY = -ymax;
mVelY = 0;
}
}
}
/*
* A particle system is just a collection of particles
*/
class ParticleSystem {
static final int NUM_PARTICLES = 1;
private Particle mBalls[] = new Particle[NUM_PARTICLES];
ParticleSystem() {
/*
* Initially our particles have no speed or acceleration
*/
for (int i = 0; i < mBalls.length; i++) {
mBalls[i] = new Particle(getContext());
mBalls[i].setBackgroundResource(R.drawable.ball);
mBalls[i].setLayerType(LAYER_TYPE_HARDWARE, null);
addView(mBalls[i], new ViewGroup.LayoutParams(mDstWidth, mDstHeight));
}
}
/*
* Update the position of each particle in the system using the
* Verlet integrator.
*/
private void updatePositions(float sx, float sy, long timestamp) {
final long t = timestamp;
if (mLastT != 0) {
final float dT = (float) (t - mLastT) / 1000.f /** (1.0f / 1000000000.0f)*/;
final int count = mBalls.length;
for (int i = 0; i < count; i++) {
Particle ball = mBalls[i];
ball.computePhysics(sx, sy, dT);
}
}
mLastT = t;
}
/*
* Performs one iteration of the simulation. First updating the
* position of all the particles and resolving the constraints and
* collisions.
*/
public void update(float sx, float sy, long now) {
// update the system's positions
updatePositions(sx, sy, now);
// We do no more than a limited number of iterations
final int NUM_MAX_ITERATIONS = 2; //nyy changed from 10 to 1
/*
* Resolve collisions, each particle is tested against every
* other particle for collision. If a collision is detected the
* particle is moved away using a virtual spring of infinite
* stiffness.
*/
boolean more = true;
final int count = mBalls.length;
for (int k = 0; k < NUM_MAX_ITERATIONS && more; k++) {
more = false;
for (int i = 0; i < count; i++) {
Particle curr = mBalls[i];
for (int j = i + 1; j < count; j++) {
Particle ball = mBalls[j];
float dx = ball.mPosX - curr.mPosX;
float dy = ball.mPosY - curr.mPosY;
float dd = dx * dx + dy * dy;
// Check for collisions
if (dd <= sBallDiameter2) {
/*
* add a little bit of entropy, after nothing is
* perfect in the universe.
*/
dx += ((float) Math.random() - 0.01f) * 0.0001f; // 0.05 changed to 0.01 will change the animation pattern and will
dy += ((float) Math.random() - 0.01f) * 0.0001f; // 0.0001 chnaged to .001
dd = dx * dx + dy * dy;
// simulate the spring
final float d = (float) Math.sqrt(dd);
final float c = (0.5f * (sBallDiameter - d)) / d;
final float effectX = dx * c;
final float effectY = dy * c;
curr.mPosX -= effectX;
curr.mPosY -= effectY;
ball.mPosX += effectX;
ball.mPosY += effectY;
more = true;
}
}
curr.resolveCollisionWithBounds();
}
}
}
public int getParticleCount() {
return mBalls.length;
}
public float getPosX(int i) {
return mBalls[i].mPosX;
}
public float getPosY(int i) {
return mBalls[i].mPosY;
}
}
public void startSimulation() {
/*
* It is not necessary to get accelerometer events at a very high
* rate, by using a slower rate (SENSOR_DELAY_UI), we get an
* automatic low-pass filter, which "extracts" the gravity component
* of the acceleration. As an added benefit, we use less power and
* CPU resources.
*/
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_GAME);
}
public void stopSimulation() {
mSensorManager.unregisterListener(this);
Toast.makeText( getApplicationContext(), "Accelerometer Disengaged", Toast.LENGTH_SHORT ).show();
}
public SimulationView(Context context) {
super(context);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
DisplayMetrics metrics = new DisplayMetrics();
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN,
WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
getWindowManager().getDefaultDisplay().getMetrics(metrics);
mXDpi = metrics.xdpi;
mYDpi = metrics.ydpi;
//this will reduce the size of the ball oroginal was 0.0254 changed t 0.0854
mMetersToPixelsX = mXDpi / 0.00154f;
mMetersToPixelsY = mYDpi / 0.00154f;
// rescale the ball so it's about 0.5 cm on screen
mDstWidth = (int) (sBallDiameter * mMetersToPixelsX * 0.5f);
mDstHeight = (int) (sBallDiameter * mMetersToPixelsY * 0.5f);
mParticleSystem = new ParticleSystem();
Options opts = new Options();
opts.inDither = true;
opts.inPreferredConfig = Bitmap.Config.RGB_565;
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
// compute the origin of the screen relative to the origin of
// the bitmap
mXOrigin = (w - mDstWidth) * 0.5f;
mYOrigin = (h - mDstHeight) * 0.5f;
mHorizontalBound = ((w / mMetersToPixelsX - sBallDiameter) * 0.5f);
mVerticalBound = ((h / mMetersToPixelsY - sBallDiameter) * 0.5f);
}
#Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER)
return;
/*
* record the accelerometer data, the event's timestamp as well as
* the current time. The latter is needed so we can calculate the
* "present" time during rendering. In this application, we need to
* take into account how the screen is rotated with respect to the
* sensors (which always return data in a coordinate space aligned
* to with the screen in its native orientation).
*/
switch (mDisplay.getRotation()) {
case Surface.ROTATION_0:
mSensorX = event.values[0];
mSensorY = event.values[1];
break;
case Surface.ROTATION_90:
mSensorX = -event.values[1];
mSensorY = event.values[0];
break;
case Surface.ROTATION_180:
mSensorX = -event.values[0];
mSensorY = -event.values[1];
break;
case Surface.ROTATION_270:
mSensorX = event.values[1];
mSensorY = -event.values[0];
break;
}
}
#Override
protected void onDraw(Canvas canvas) {
/*
* Compute the new position of our object, based on accelerometer
* data and present time.
*/
final ParticleSystem particleSystem = mParticleSystem;
final long now = System.currentTimeMillis();
final float sx = mSensorX;
final float sy = mSensorY;
particleSystem.update(sx, sy, now);
final float xc = mXOrigin;
final float yc = mYOrigin;
final float xs = mMetersToPixelsX;
final float ys = mMetersToPixelsY;
final int count = particleSystem.getParticleCount();
for (int i = 0; i < count; i++) {
/*
* We transform the canvas so that the coordinate system matches
* the sensors coordinate system with the origin in the center
* of the screen and the unit is the meter.
*/
final float x = xc + particleSystem.getPosX(i) * xs;
final float y = yc - particleSystem.getPosY(i) * ys;
particleSystem.mBalls[i].setTranslationX(x);
particleSystem.mBalls[i].setTranslationY(y);
}
// and make sure to redraw asap
invalidate();
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
}

SurfaceView Runnable with Android location manager

Hi I currently have a SurfaceView Runnable public class mapsLayout extends SurfaceView implements Runnable { which draws lines based on current geolocation. My previous solution involved having a main activity which contains the Android location manager - using a FusedLocationProviderClient as recommended by the tutorials provided by Google - and then calling the SurfaceView.
mainActivity with Android location manager -> 'SurfaceView'
However this means that the SurfaceView resets every time the location changes which happens every 10000 ticks.
Is there a way for the SurfaceView to contain the Android location manager.
If it helps I have my SurfaceView Runnable code below
public class mapsActivityLayout extends SurfaceView implements Runnable {
MyThread draw = null;
boolean canDraw = false;
Bitmap map;
SurfaceHolder surfaceHolder;
Context mContext;
Paint paint;
ArrayList<String> endNodes = new ArrayList<String>();
int bitmapX;
int bitmapY;
int viewWidth;
int viewHeight;
Paint red_paintbrush_fill, blue_paintbrush_fill, green_paintbrush_fill;
Paint red_paintbrush_stroke, blue_paintbrush_stroke, green_paintbrush_stroke;
Path line;
Path circle;
public mapsActivityLayout(Context context, ArrayList<String> endNodes) {
super(context);
this.endNodes = endNodes
mContext = context;
surfaceHolder = getHolder();
paint = new Paint();
paint.setColor(Color.DKGRAY);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
viewWidth = w;
viewHeight = h;
draw = new MyThread(viewWidth, viewHeight);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inScaled = true;
options.inMutable = true;
map = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.mapimage, options);
setUpBitmap();
}
#Override
public void run() {
Canvas canvas;
prepPaintBrushes();
while (canDraw) {
//draw stuff
if (surfaceHolder.getSurface().isValid()) {
int x = draw.getX();
int y = draw.getY();
//int radius = draw.getRadius();
canvas = surfaceHolder.lockCanvas();
canvas.save();
canvas.drawBitmap(map, bitmapX, bitmapY, paint);
ArrayList<Double> currentLocation = convertGeoToPixel(currentLat, currentLon);
ArrayList<Double> destination = convertGeoToPixel(destinationLat, destinationLat);
int width = 2699;
int height = 2699;
canvas.drawCircle(currentX, currentY, 20, red_paintbrush_fill);
canvas.drawCircle(destX, destY, 20, green_paintbrush_fill);
path.rewind();
canvas.restore();
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
private void updateFrame(int newX, int newY) {
draw.update(newX, newY);
}
/**
* Calculates a randomized location for the bitmap
* and the winning bounding rectangle.
*/
private void setUpBitmap() {
bitmapX = (int) Math.floor(
Math.random() * (viewWidth - backGround.getWidth()));
bitmapY = (int) Math.floor(
Math.random() * (viewHeight - backGround.getHeight()));
}
public void pause() {
canDraw = false;
while (true) {
try {
thread.join();
break;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void resume() {
canDraw = true;
thread = new Thread(this);
thread.start();
}
private void prepPaintBrushes() {
red_paintbrush_fill = new Paint();
red_paintbrush_fill.setColor(Color.RED);
red_paintbrush_fill.setStyle(Paint.Style.FILL);
green_paintbrush_stroke = new Paint();
green_paintbrush_stroke.setColor(Color.GREEN);
green_paintbrush_stroke.setStyle(Paint.Style.STROKE);
green_paintbrush_stroke.setStrokeWidth(10);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
setUpBitmap();
updateFrame((int) x, (int) y);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
updateFrame((int) x, (int) y);
invalidate();
break;
default:
}
return true;
}
}
thread code
public class MyThread extends Thread {
private int mX;
private int mY;
public MyThread(int viewWidth, int viewHeight) {
//super()
mX = viewWidth / 2;
mY = viewHeight / 2;
}
/**
* Update the coordinates of the map.
*
* #param newX Changed value for x coordinate.
* #param newY Changed value for y coordinate.
*/
public void update(int newX, int newY) {
mX = newX;
mY = newY;
}
public int getX() {
return mX;
}
public int getY() {
return mY;
}
}

Make touchable bg of touchpad [LibGdx]

Here's my touchpad.
What I want is this: when I touch background of touchpad (not knob), knob move to this position. Code, which I use for touchpad from github/libgdx/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Touchpad.java
package com.liketurbo.funnyGame;
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
import com.badlogic.gdx.scenes.scene2d.Event;
import com.badlogic.gdx.scenes.scene2d.EventListener;
import com.badlogic.gdx.scenes.scene2d.ui.Widget;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.math.Circle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener.ChangeEvent;
import com.badlogic.gdx.scenes.scene2d.utils.Drawable;
import com.badlogic.gdx.utils.Pools;
/** An on-screen joystick. The movement area of the joystick is circular, centered on the touchpad, and its size determined by the
* smaller touchpad dimension.
* <p>
* The preferred size of the touchpad is determined by the background.
* <p>
* {#link ChangeEvent} is fired when the touchpad knob is moved. Cancelling the event will move the knob to where it was
* previously.
* #author Josh Street */
public class Touchpad extends Widget {
private TouchpadStyle style;
boolean touched;
boolean resetOnTouchUp = true;
private float deadzoneRadius;
private final Circle knobBounds = new Circle(0, 0, 0);
private final Circle touchBounds = new Circle(0, 0, 0);
private final Circle deadzoneBounds = new Circle(0, 0, 0);
private final Vector2 knobPosition = new Vector2();
private final Vector2 knobPercent = new Vector2();
/** #param deadzoneRadius The distance in pixels from the center of the touchpad required for the knob to be moved. */
public Touchpad (float deadzoneRadius, Skin skin) {
this(deadzoneRadius, skin.get(TouchpadStyle.class));
}
/** #param deadzoneRadius The distance in pixels from the center of the touchpad required for the knob to be moved. */
public Touchpad (float deadzoneRadius, Skin skin, String styleName) {
this(deadzoneRadius, skin.get(styleName, TouchpadStyle.class));
}
/** #param deadzoneRadius The distance in pixels from the center of the touchpad required for the knob to be moved. */
public Touchpad (float deadzoneRadius, TouchpadStyle style) {
if (deadzoneRadius < 0) throw new IllegalArgumentException("deadzoneRadius must be > 0");
this.deadzoneRadius = deadzoneRadius;
knobPosition.set(getWidth() / 2f, getHeight() / 2f);
setStyle(style);
setSize(getPrefWidth(), getPrefHeight());
addListener(new InputListener() {
#Override
public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
if (touched) return false;
touched = true;
calculatePositionAndValue(x, y, false);
return true;
}
#Override
public void touchDragged (InputEvent event, float x, float y, int pointer) {
calculatePositionAndValue(x, y, false);
}
#Override
public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
touched = false;
calculatePositionAndValue(x, y, resetOnTouchUp);
}
});
}
void calculatePositionAndValue (float x, float y, boolean isTouchUp) {
float oldPositionX = knobPosition.x;
float oldPositionY = knobPosition.y;
float oldPercentX = knobPercent.x;
float oldPercentY = knobPercent.y;
float centerX = knobBounds.x;
float centerY = knobBounds.y;
y = centerY;
knobPosition.set(centerX, centerY);
knobPercent.set(0f, 0f);
if (!isTouchUp) {
if (!deadzoneBounds.contains(x, y)) {
knobPercent.set((x - centerX) / knobBounds.radius*3.5f, 0);
float length = knobPercent.len();
if (length > 1) knobPercent.scl(1 / length);
if (knobBounds.contains(x, y)) {
knobPosition.set(x, y);
} else {
knobPosition.set(knobPercent).nor().scl(knobBounds.radius*3.5f).add(knobBounds.x, knobBounds.y);
}
}
}
if (oldPercentX != knobPercent.x || oldPercentY != knobPercent.y) {
ChangeEvent changeEvent = Pools.obtain(ChangeEvent.class);
if (fire(changeEvent)) {
knobPercent.set(oldPercentX, oldPercentY);
knobPosition.set(oldPositionX, oldPositionY);
}
Pools.free(changeEvent);
}
}
public void setStyle (TouchpadStyle style) {
if (style == null) throw new IllegalArgumentException("style cannot be null");
this.style = style;
invalidateHierarchy();
}
/** Returns the touchpad's style. Modifying the returned style may not have an effect until {#link #setStyle(TouchpadStyle)} is
* called. */
public TouchpadStyle getStyle () {
return style;
}
#Override
public Actor hit (float x, float y, boolean touchable) {
return touchBounds.contains(x, y) ? this : null;
}
#Override
public void layout () {
// Recalc pad and deadzone bounds
float halfWidth = getWidth() / 2;
float halfHeight = getHeight() / 2;
float radius = Math.min(halfWidth, halfHeight);
touchBounds.set(halfWidth, halfHeight, radius);
if (style.knob != null) radius -= Math.max(style.knob.getMinWidth(), style.knob.getMinHeight()) / 2;
knobBounds.set(halfWidth, halfHeight, radius);
deadzoneBounds.set(halfWidth, halfHeight, deadzoneRadius);
// Recalc pad values and knob position
knobPosition.set(halfWidth, halfHeight);
knobPercent.set(0, 0);
}
#Override
public void draw (Batch batch, float parentAlpha) {
validate();
Color c = getColor();
batch.setColor(c.r, c.g, c.b, c.a * parentAlpha);
float x = getX();
float y = getY();
float w = getWidth();
float h = getHeight();
final Drawable bg = style.background;
if (bg != null) bg.draw(batch, x, y, w, h);
final Drawable knob = style.knob;
if (knob != null) {
x += knobPosition.x - (knob.getMinWidth()*2) / 2f;
y += knobPosition.y - (knob.getMinHeight()*2) / 2f;
knob.draw(batch, x, y, knob.getMinWidth()*2, knob.getMinHeight()*2);
}
}
#Override
public float getPrefWidth () {
return style.background != null ? style.background.getMinWidth() : 0;
}
#Override
public float getPrefHeight () {
return style.background != null ? style.background.getMinHeight() : 0;
}
public boolean isTouched () {
return touched;
}
public boolean getResetOnTouchUp () {
return resetOnTouchUp;
}
/** #param reset Whether to reset the knob to the center on touch up. */
public void setResetOnTouchUp (boolean reset) {
this.resetOnTouchUp = reset;
}
/** #param deadzoneRadius The distance in pixels from the center of the touchpad required for the knob to be moved. */
public void setDeadzone (float deadzoneRadius) {
if (deadzoneRadius < 0) throw new IllegalArgumentException("deadzoneRadius must be > 0");
this.deadzoneRadius = deadzoneRadius;
invalidate();
}
/** Returns the x-position of the knob relative to the center of the widget. The positive direction is right. */
public float getKnobX () {
return knobPosition.x;
}
/** Returns the y-position of the knob relative to the center of the widget. The positive direction is up. */
public float getKnobY () {
return knobPosition.y;
}
/** Returns the x-position of the knob as a percentage from the center of the touchpad to the edge of the circular movement
* area. The positive direction is right. */
public float getKnobPercentX () {
return knobPercent.x;
}
/** Returns the y-position of the knob as a percentage from the center of the touchpad to the edge of the circular movement
* area. The positive direction is up. */
public float getKnobPercentY () {
return knobPercent.y;
}
/** The style for a {#link Touchpad}.
* #author Josh Street */
public static class TouchpadStyle {
/** Stretched in both directions. Optional. */
public Drawable background;
/** Optional. */
public Drawable knob;
public TouchpadStyle () {
}
public TouchpadStyle (Drawable background, Drawable knob) {
this.background = background;
this.knob = knob;
}
public TouchpadStyle (TouchpadStyle style) {
this.background = style.background;
this.knob = style.knob;
}
}
}
Line addListener(new InputListener() {...} works only for knob, if I can figure out how make it work for touchpad's background too, it solved my problem. Does somebody know how solve this problem? Thank you in advance.
You shouldn't add listener to your touchpad. Just limit touch area of the screen where touchpad can be used.
Here is code to activate only on right half of a screen:
private Touchpad touchpad;
private Vector2 screenPos = new Vector2(); // position where touch occurs
private Vector2 localPos = new Vector2(); // position in local coordinates
private InputEvent fakeTouchDownEvent = new InputEvent(); // fake touch for correct work
private Vector2 stagePos; // position to fire touch event
private void getDirection() {
if (Gdx.input.justTouched()) {
// Get the touch point in screen coordinates.
screenPos.set(Gdx.input.getX(), Gdx.input.getY());
if (screenPos.x > Gdx.graphics.getWidth() / 2) { // right half of a screen
// Convert the touch point into local coordinates, place the touchpad and show it.
localPos.set(screenPos);
localPos = touchpad.getParent().screenToLocalCoordinates(localPos);
touchpad.setPosition(localPos.x - touchpad.getWidth() / 2, localPos.y - touchpad.getHeight() / 2);
// Fire a touch down event to get the touchpad working.
Vector2 stagePos = touchpad.getStage().screenToStageCoordinates(screenPos);
fakeTouchDownEvent.setStageX(stagePos.x);
fakeTouchDownEvent.setStageY(stagePos.y);
touchpad.fire(fakeTouchDownEvent);
}
}
}

JavaFX Asteroids Game Clone: Having trouble bouncing asteroids off eachother

I am trying to make an Asteroids game clone in JavaFX. So far, I have been able to draw the ship and asteroids onto the screen (where Rectangles represent them, for now). I have also implemented movement for the ship, and randomized movements for the asteroids.
I am having trouble implementing the code needed to bounce the asteroids off each other. The current method that does the collision checking (called checkAsteroidCollisions) is bugged in that all asteroids start stuttering in place. They don't move, but rather oscillate back and forth in place rapidly. Without the call to this method, all asteroids begin moving normally and as expected.
Instead, I want each asteroid to move freely and, when coming into contact with another asteroid, bounce off each other like in the actual Asteroids game.
MainApp.java
import java.util.ArrayList;
import java.util.HashSet;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class MainApp extends Application {
private static final int WIDTH = 700;
private static final int HEIGHT = 900;
private static final int NUM_OF_ASTEROIDS = 12;
private static final Color ASTEROID_COLOR = Color.GRAY;
private static final Color PLAYER_COLOR = Color.BLUE;
private Player player;
private ArrayList<Entity> asteroids;
long lastNanoTime; // For AnimationTimer
HashSet<String> inputs; // For inputs
private static final int MAX_SPEED = 150;
private static final int SPEED = 10;
private static final int ASTEROID_SPEED = 150;
private StackPane background;
/*
* Generates a random number between min and max, inclusive.
*/
private float genRandom(int min, int max) {
return (float) Math.floor(Math.random() * (max - min + 1) + min);
}
/*
* Initializes the asteroids
*/
private void initAsteroids() {
this.asteroids = new ArrayList<Entity>();
for (int i = 0; i < NUM_OF_ASTEROIDS; i++) {
Entity asteroid = new Entity(50, 50, ASTEROID_COLOR, EntityType.ASTEROID);
float px = (float) genRandom(200, WIDTH - 50);
float py = (float) genRandom(200, HEIGHT - 50);
asteroid.setPos(px, py);
// Keep recalculating position until there are no collisions
while (asteroid.intersectsWith(this.asteroids)) {
px = (float) genRandom(200, WIDTH - 50);
py = (float) genRandom(200, HEIGHT - 50);
asteroid.setPos(px, py);
}
// Randomly generate numbers to change velocity by
float dx = this.genRandom(-ASTEROID_SPEED, ASTEROID_SPEED);
float dy = this.genRandom(-ASTEROID_SPEED, ASTEROID_SPEED);
asteroid.changeVelocity(dx, dy);
this.asteroids.add(asteroid);
}
}
/*
* Initializes the player
*/
private void initPlayer() {
this.player = new Player(30, 30, PLAYER_COLOR, EntityType.PLAYER);
this.player.setPos(WIDTH / 2, 50);
}
/*
* Checks collisions with screen boundaries
*/
private void checkOffScreenCollisions(Entity e) {
if (e.getX() < -50)
e.setX(WIDTH);
if (e.getX() > WIDTH)
e.setX(0);
if (e.getY() < -50)
e.setY(HEIGHT);
if (e.getY() > HEIGHT)
e.setY(0);
}
/*
* Controls speed
*/
private void controlSpeed(Entity e) {
if (e.getDx() < -MAX_SPEED)
e.setDx(-MAX_SPEED);
if (e.getDx() > MAX_SPEED)
e.setDx(MAX_SPEED);
if (e.getDy() < -MAX_SPEED)
e.setDy(-MAX_SPEED);
if (e.getDy() > MAX_SPEED)
e.setDy(MAX_SPEED);
}
/*
* Controls each asteroid's speed and collision off screen
*/
private void controlAsteroids(ArrayList<Entity> asteroids) {
for (Entity asteroid : asteroids) {
this.checkOffScreenCollisions(asteroid);
this.controlSpeed(asteroid);
}
}
/*
* Checks an asteroid's collision with another asteroid
*/
private void checkAsteroidCollisions() {
for (int i = 0; i < NUM_OF_ASTEROIDS; i++) {
Entity asteroid = this.asteroids.get(i);
if (asteroid.intersectsWith(this.asteroids)){
float dx = (float) asteroid.getDx();
float dy = (float) asteroid.getDy();
asteroid.setDx(0);
asteroid.setDy(0);
asteroid.changeVelocity(-dx, -dy);
}
}
}
#Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("Hello World!");
this.initAsteroids();
this.initPlayer();
background = new StackPane();
background.setStyle("-fx-background-color: pink");
this.inputs = new HashSet<String>();
Group root = new Group();
Scene scene = new Scene(root);
primaryStage.setScene(scene);
scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent e) {
String code = e.getCode().toString();
inputs.add(code);
}
});
scene.setOnKeyReleased(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent e) {
String code = e.getCode().toString();
inputs.remove(code);
}
});
Canvas canvas = new Canvas(WIDTH, HEIGHT);
GraphicsContext gc = canvas.getGraphicsContext2D();
background.getChildren().add(canvas);
root.getChildren().add(background);
lastNanoTime = System.nanoTime();
new AnimationTimer() {
#Override
public void handle(long currentNanoTime) {
float elapsedTime = (float) ((currentNanoTime - lastNanoTime) / 1000000000.0);
lastNanoTime = currentNanoTime;
/* PLAYER */
// Game Logic
if (inputs.contains("A"))
player.changeVelocity(-SPEED, 0);
if (inputs.contains("D"))
player.changeVelocity(SPEED, 0);
if (inputs.contains("W"))
player.changeVelocity(0, -SPEED);
if (inputs.contains("S"))
player.changeVelocity(0, SPEED);
// Collision with edge of map
checkOffScreenCollisions(player);
// Control speed
controlSpeed(player);
player.update(elapsedTime);
/* ASTEROIDS */
gc.setFill(ASTEROID_COLOR);
for(int i = 0; i < NUM_OF_ASTEROIDS; i++) {
checkAsteroidCollisions(i); // BUGGY CODE
}
controlAsteroids(asteroids);
gc.clearRect(0, 0, WIDTH, HEIGHT);
for (Entity asteroid : asteroids) {
asteroid.update(elapsedTime);
asteroid.render(gc);
}
gc.setFill(PLAYER_COLOR);
player.render(gc);
}
}.start();
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Entity.java:
import java.util.ArrayList;
import javafx.geometry.Rectangle2D;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
public class Entity {
private Color color;
private double x, y, width, height, dx, dy;
private EntityType entityType; // ID of this Entity
public Entity(float width, float height, Color color, EntityType type) {
this.x = this.dx = 0;
this.y = this.dy = 0;
this.width = width;
this.height = height;
this.color = color;
this.entityType = type;
}
/*
* Getters and setters
*/
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public double getX() {
return x;
}
public void setX(float x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(float y) {
this.y = y;
}
public double getDx() {
return dx;
}
public void setDx(float dx) {
this.dx = dx;
}
public double getDy() {
return dy;
}
public void setDy(float dy) {
this.dy = dy;
}
public EntityType getEntityType() {
return entityType;
}
/*
* Adds to dx and dy (velocity)
*/
public void changeVelocity(float dx, float dy) {
this.dx += dx;
this.dy += dy;
}
/*
* Sets position
*/
public void setPos(float x, float y) {
this.setX(x);
this.setY(y);
}
/*
* Gets new position of the Entity based on velocity and time
*/
public void update(float time) {
this.x += this.dx * time;
this.y += this.dy * time;
}
/*
* Used for collisions
*/
public Rectangle2D getBoundary() {
return new Rectangle2D(this.x, this.y, this.width, this.height);
}
/*
* Checks for intersections
*/
public boolean intersectsWith(Entity e) {
return e.getBoundary().intersects(this.getBoundary());
}
/*
* If any of the entities in the passed in ArrayList
* intersects with this, then return true;
*/
public boolean intersectsWith(ArrayList<Entity> entities) {
for(Entity e : entities) {
if(e.getBoundary().intersects(this.getBoundary()))
return true;
}
return false;
}
/*
* Draws the shape
*/
public void render(GraphicsContext gc) {
gc.fillRoundRect(x, y, width, height, 10, 10);
}
#Override
public String toString() {
return "Entity [x=" + x + ", y=" + y + ", width=" + width + ", height=" + height + ", entityType=" + entityType
+ "]";
}
}
I think you will need to change the position of the two colliding asteroids slightly so their state is not on collision anymore.
What happens right now is that you change their movement after the collision but I guess that your algorithm notices that they are still touching, so it will try to change the movement again with the same result as before.
What you need to implement now is a change in the position of the two asteroids so your collision detection won´t act up again immediately after it´s first call.
I hope I could help you.

Android Animation Clockwise

I have the next code for move a image in 360 degree but I want to move the image in certain degree when the I touch the screen. For instance, when the screen is touched the image move in 10 degree in closewise or anticlosewise direction.
please help me I am stuck with a project.
I want something like this.
In this image you can see how i want to implement.
Thanks in advance.
MainActivity.java
public class Tablero extends Activity {
private ImageView imagen;
private TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tablero);
tv = (TextView) findViewById(R.id.tableroTv);
imagen = (ImageView) findViewById(R.id.tableroAnimacion);
imagen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int numero = (int)(Math.random()*6)+1;
Animation anim = new Animacion(getApplicationContext(),
imagen, 300);
anim.setDuration(3000);
imagen.startAnimation(anim);
tv.setText(numero+"");
}
});
}
}
Animation.java
public class Animacion extends Animation {
private View view;
private float cx, cy;
private float prevX, prevY;
private float r;
private Context context;
private float angulo;
private int cont=0;
public Animacion(Context context, View view, float r) {
this.context = context;
this.view = view;
this.r = r;
angulo = 90f;
}
#Override
public boolean willChangeBounds() {
return true;
}
#Override
public void initialize(int width, int height, int parentWidth,
int parentHeight) {
int cxImage = width / 2;
int cyImage = height / 2;
cx = view.getLeft() + cxImage;
cy = view.getTop() + cyImage;
prevX = cx;
prevY = cy;
}
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
if (interpolatedTime == 0) {
return;
}
//float angleDeg = (interpolatedTime * 360f + 90) % 360;
float angleDeg = (interpolatedTime * 60f + 90) % 360;
// float angleDeg = angulo;
float angleRad = (float) Math.toRadians(angleDeg);
//Log.d("animacion", "grados " + angleDeg);
//Log.d("animacion", "radianes " + angleRad);
float x = (float) (cx + r * Math.cos(angleRad));
float y = (float) (cy + r * Math.sin(angleRad));
float dx = prevX - x;
float dy = prevY - y;
Log.d("animacion", "x: " + x + " y : " + y
+" dx: " + dx + " dy: " +dy);
t.getMatrix().setTranslate(dx, dy);
}
public void setAngulo(float grados){
this.angulo = grados;
}
public float getAngulo(){
return this.angulo;
}
}
One of your first steps is going to be detecting touch input and deciding what to do with it. Have a look at this: OnTouchListener in a View - Android
Basically you want to make your Activity implement the OnTouchListener interface and provide an overridden version of the onTouch(View v, MotionEvent event) method. In here you extract the event action and handle it as necessary.
This will also help: http://developer.android.com/reference/android/view/MotionEvent.html
The ACTION_DOWN event occurs when a user puts their finger on the screen. The ACTION_MOVE event occurs when a user has touched the screen and is moving their finger without lifting it from the screen. ACTION_UP is when the user removes their finger from the screen. The reason I point all of this out is that if you want something to happen while the user holds their finger down and doesn't move it, you will have to have some variable set to true for example when ACTION_DOWN occurs, and false when ACTION_UP occurs. So when the variable is true, the rotation keeps happening, 10 degrees at a time. The other way of course is to have the rotation happen once on ACTION_DOWN and then repeat on ACTION_MOVE as the user moves their finger. You can also call .getX() and .getY() on the MotionEvent variable that will let you know where the user touched and potentially work out what direction they are moving their finger in etc.

Categories

Resources