Andengine PhysicsHandler makes player look laggy - java

Hey my problem is that in the onUpdate in PhysicsHandler the pSecondsElapsed often jumps from 0.016... to 0.038 which makes the player move in such big steps that it looks like the player would lagg.
Here to the importante Code from the onUpdate :
#Override
protected void onUpdate(final float pSecondsElapsed, final IEntity pEntity) {
if(this.mEnabled) {
/* Apply linear acceleration. */
final float accelerationX = this.mAccelerationX;
final float accelerationY = this.mAccelerationY;
if(accelerationX != 0 || accelerationY != 0) {
this.mVelocityX += accelerationX * pSecondsElapsed;
this.mVelocityY += accelerationY * pSecondsElapsed;
}
/* Apply angular velocity. */
final float angularVelocity = this.mAngularVelocity;
if(angularVelocity != 0) {
pEntity.setRotation(pEntity.getRotation() + angularVelocity * pSecondsElapsed);
}
/* Apply linear velocity. */
final float velocityX = this.mVelocityX;
final float velocityY = this.mVelocityY;
if(velocityX != 0 || velocityY != 0) {
pEntity.setPosition(pEntity.getX() + velocityX * pSecondsElapsed, pEntity.getY() + velocityY * pSecondsElapsed);
}
}
}
btw I am only using the linear velocity. Does anyone have a solution for this? Thanks for your help!

I went ahead and looked through the repository for this engine and I found a class that may be a help to you. The base engine class has an extension called Fixed Step Engine that should allow you to control the delta time per frame, which may be worth trying out (if you haven't already) for smoother physics.

In combination with FixedStepPhysicsWorld you will get the best possible result but: There is a small "mistake" inside the FixedStepPhysicsWorld class:
Change onUpdate as follows:
...
while(this.mSecondsElapsedAccumulator >= stepLength && stepsAllowed > 0) {
world.step(stepLength, velocityIterations, positionIterations);
this.mSecondsElapsedAccumulator -= stepLength;
stepsAllowed--;
}
this.mPhysicsConnectorManager.onUpdate(pSecondsElapsed);
to
...
while(this.mSecondsElapsedAccumulator >= stepLength && stepsAllowed > 0) {
world.step(stepLength, velocityIterations, positionIterations);
this.mSecondsElapsedAccumulator -= stepLength;
stepsAllowed--;
this.mPhysicsConnectorManager.onUpdate(stepLength);
}
The problem in the original code is that the PhysicsConnectors get updated after the PhysicsWorld made multiple steps (most of the cases). My code fixes this issue. Whenever the UiThread draws the connected entities, they are always at the position where their connected bodies are. They do not skip a Physics-step.

Related

Slick2d Java reversing the moving direction of an object

I'm working on this game using Java and slick2d library and I'm supposed to reverse the direction of some moving vehicles (eg:bikes) when they reach a certain x-coordinate.
Logic seems simple enough, yet some of them move right past the x-coordinate, while some reverses the direction. Confused as to why. Any help would be appreciated.
Here's my code in the update() method. getX() returns the x location from superclass as a float. BIKE_SPEED is a float, delta being the milliseconds passed since last frame.
#Override
public void update(Input input, int delta) {
if ((int)getX() == 24 || (int)getX() == 1000) {
moveRight = !moveRight;
}
move(BIKE_SPEED * delta * (moveRight ? 1 : -1), 0);
}
I'm not familiar with slick2d, but in general, it's better to use >= or <= instead of == in cases like this. The object (bike) may "jump" right past the boundaries, without triggering your change of direction condition.

measure distance without network

I want to know how I can use accelerometer sensor to determine distance that I an walk it at Android device If it is possible, then how can I implement it?
I use this code but not run. Any answer please??
#Override
public void onSensorChanged(SensorEvent event) {
float[] values = event.values;
int value = -1;
if (values.length > 0) {
value = (int) values[0];
}
if(event.sensor.getType()==Sensor.TYPE_STEP_DETECTOR) {
steps++;
}
}
float distance = (float)(steps*68.475)/(float)100000;
It is not possible: due to the low sensitivity of the built-in accelerometers and the so weak accelerations that are created when a person walks.
Not having network does not mean that GPS does not work ...

How to make Bug object move five times using recursive function?

I am learning Java from the book written by Allen B. Downey, "Think Java". In chapter 5, it is being introduced the notion of GridWorld where you basically have a grid 10x10 with "actors" such as a Bug, a Rocks and Grid itself, which represents objects. When the code is installed, the GridWorld GUI will show a grid containing two actors, a "bug" and a "rock".
By clicking on the actor, there is a drop-down menu with methods, which can be called upon that actor.
One of the assignments is to write a method, by using Math.random(); named randomBug that takes a Bug as a parameter and sets the Bug's direction to one of 0, 90, 180 or 270, that is North, East, South, West, with equal probability, and then moves the bug if it can.
Next assignment is to modify randomBug to take an integer n and repeat n times.
This is my code:
/*
* AP(r) Computer Science GridWorld Case Study:
* Copyright(c) 2005-2006 Cay S. Horstmann (http://horstmann.com)
*
* This code is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* #author Cay Horstmann
*/
import info.gridworld.actor.ActorWorld;
import info.gridworld.actor.Bug;
import info.gridworld.actor.Rock;
/**
* This class runs a world that contains a bug and a rock, added at random
* locations. Click on empty locations to add additional actors. Click on
* populated locations to invoke methods on their occupants. <br />
* To build your own worlds, define your own actors and a runner class. See the
* BoxBugRunner (in the boxBug folder) for an example. <br />
* This class is not tested on the AP CS A and AB exams.
*/
public class BugRunner
{
public static void main(String[] args)
{
ActorWorld world = new ActorWorld();
Bug redbug = new Bug();
world.add(redbug);
System.out.println(redbug.getLocation());
world.show();
randomBug(redbug, Math.random(), 5);
}
public static void randomBug(Bug x, double y, int n){
if (y <= 0.2 && n >= 0){
x.setDirection(0);
if (x.canMove()) x.move();
} else if (y >= 0.3 && y <= 0.5 && n >= 0){
x.setDirection(90);
if (x.canMove()) x.move();
} else if (y >= 0.6 && y <= 0.8 && n >= 0){
x.setDirection(180);
if (x.canMove()) x.move();
} else {
x.setDirection(270);
if (x.canMove()) x.move();
}
randomBug(x, Math.random(), n-1);
}
}
I am trying to use recursive function to repeat the process five times, so the Bug should move five times, unless it reaches the edge of the Grid. The problem that sometimes occurs is that the Bug moves more then 5 times, it makes 6 or 10 steps, even though I limited it by using condition n <= 0.
What should I change or add in my code so that I can accomplish assignment ?
First of all, you should keep your code as simple as possible, try to separate repeating elements as much as possible (your code has at least 2).
Second, when your n reaches 0 it fails all checks and moves on to the else condition. Then it keeps going in that direction until it can't anymore. I'm surprised you haven't gotten a stackoverflow yet.
in the end your code should look a bit like this:
void randomBug(Bug x, double y, int n)
{
if( n <= 0 ) //separated repeated use of requirement
return;
if( [...] )
x.setDirection( ... );
else if ( [...] )
x.setDirection( ... );
[ more else ifs as needed ]
if( x.canMove() ) //separated repeated use of action
x.move();
randomBug(x, Math.random(), n-1);
}
Lastly, you keep checking if your random is between two values, that is not needed in this particular case:
if( y <= .25 )
// do if smaller than .25
else if( y <= .5 ) //no need to check inbetween
// do if smaller than .5
there is no need to check in the second if statement if it is also larger than .25 since your first check already confirmed that it is.
The problem is that you always call randomBug(x, Math.random(), n-1); at the end. You never return from the method. This is an infinite loop.
To fix this, I would remove the n >= 0 test from all the branches, and just add this test at the top of the function.
if (n < 0) return; // Or n <= 0?
This if-test is called the base case of your recursive function.
Is this a bit better ? I have tried it, it seems it works...
public static void randomBug(Bug x, double y, int n){
if (n <= 0) return;
if (y <= 0.2){
x.setDirection(0);
} else if (y <= 0.5){
x.setDirection(90);
} else if (y <= 0.8){
x.setDirection(180);
} else {
x.setDirection(270);
}
if (x.canMove()) x.move();
randomBug(x, Math.random(), n-1);
}

Decreasing One Variable as Another Increases

I am putting together a small game in Java, one of the problems I have encountered is increasing the speed of the animation as the player character's movement speed increases.
To increase the speed of animation, the time each frame of the animation is displayed must be decreased, from a maximum of '0.2' for the slowest speed and '0.1' for the highest speed.
My current code works, but it is quite clearly a little clumsy. Unfortunately, I can't think of an elegant solution to replace it.
public float getAnimationSpeed()
{
float _absVel = Math.abs(_vel.x);
if(_absVel > 10 && _absVel <= 50)
{
return 0.1f;
}
else if(_absVel > 50 && _absVel <= 150)
{
return 0.075f;
}
else if(_absVel > 150)
{
return 0.05f;
}
else
{
return 0f;
}
}
You might notice the function may also return a zero, which is used to display the animation as still(For example, when the player character has a velocity of 0, the animation shouldn't be playing).
You can be more dynamic, instead of reasoning with "steps" :
public float getAnimationSpeed()
{
float _absVel = Math.abs(_vel.x);
float offset = 0; //whatever you want
if(_absVel<=10){
return 0f;
}
else{
return ((1/_absVel)+offset)f;
}
}
You can of course change the "1" and the offset to another value that matches the result you want.
I hope it helped !
PS/ You probably also want to check if the result is over your maximum or under your minimum, which I didn't do.

Draw a line but I get dots and curves (java)

I made an application that displays values from a remote sensor.
It is a modification of an existing application.
What I don't understand, I ask to "Drawline", so I am expecting a line.
What I get is "pots" or "curves"....
I get no lines anymore (before was fine), and I didn't modify anything in the Drawline painting part ...
If you could enlight me and help me solve this problem, I would be much grateful !
gy = parent.parent.data.getTemperatureData(nodeId, gx);
int sy = -1;
if (gy >= 0) { // Ignore missing values
double rsy = height - yscale * (gy - gy0);
// Ignore problem values
if (rsy >= -1e6 && rsy <= 1e6) {
sy = (int)(rsy + 0.5);
}//end if
if (lastsy >= 0 && sy >= 0) {
g.drawLine(lastsx, lastsy, sx, sy);
}//end if
//}//end if
}//end if
lastsx = sx;
lastsy = sy;
This is not a java issue, but rather an issue caused by my C code on sensors. I called 3 different read functions and they all send the values, that is why all the graphs are made at the same time, and this makes a display issue. Java code is fine, I need to learn C !

Categories