Objects getting jerks when moving camera in downward direction - java

I have been making a game in which there is number of objects in negative 'y' for which I had taken the arrayList and I am moving the main character in downward direction.But when the camera move with the character the objects are not moving smooth, they are getting jerks after some interval of time.The code for that is following
#Override
public void create() {
camera = new OrthographicCamera(480, 720);
camera.position.set(480 / 2, 720 / 2, 0);
batch = new SpriteBatch();
int i;
this.baloonArrList = new ArrayList<Baloon>();
for (i = 0; i < 3000; i += 300) {
Baloon baloon = new Baloon(200, i);
baloonArrList.add(baloon);
System.out.println(baloon.balloon_y);
}
texture1 = new Texture(Gdx.files.internal("data/sheet_final.png"));
textureRegion1 = new TextureRegion(texture1, 561, 156, 115, 101);
}
#Override
public void render() {
GLCommon gl = Gdx.gl;
Gdx.gl.glClearColor(1, 1, 1, 1);
gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
camera.position.y += 4;
camera.update();
batch.setProjectionMatrix(camera.combined);
batch.begin();
int len = baloonArrList.size();
for (int i = 0; i < len; i++) {
batch.draw(textureRegion1, baloonArrList.get(i).balloon_x,
baloonArrList.get(i).balloon_y, 100, 100);
}
batch.end();
}
So, how can I make the motion of objects smooth.

I believe the source of your issue is the following line:
camera.position.y += 4;
You should instead change it to a smaller value, or better, make it based on the speed of the frame rate:
camera.position.y += 4 * Gdx.graphics.getDeltaTime();
This way your camera will move in the y direction 4 pixels every second, instead of 4 pixels every frame. (Of course you may need to increase the 4 to make it faster, but it will keep it quite smooth.)

If the rendering is jerky and inconsistent (use the builtin FPSLogger to find out what framerate you're getting), then something is taking more/variable amounts of time during rendering. You should use a profiler to figure out where time is going. The Android DDMS tools included with Eclipse are pretty good. Too-frequent garbage collection is often a source of variable runtimes, but its best to understand what is going on before trying to fix it.
That said, #Jyro117's suggestion to make your state updates frame-rate independent is always a good idea.

Related

Changing color of sphere with time (processing)

I am a new coder on processing, because of this reason please be gentle.
Normally my code is more longer and complex but I wrote a simple code for you, which I can adapt on my code:
int speed = 1;
int x, z = 50;
void setup() {
size(400, 400, P3D);
}
void draw() {
background(0);
noStroke();
lights();
translate(x, height/2, z);
fill(255,0,0);
sphere(25);
if (x > width -50)
noLoop();
x += speed;
}
So, like you see, sphere starts with color of red and it reaches end of the window. I want to change it's color from red to white and it should take 30 sec. to reach end of the window. However I don't know how. If you help me I will be happy.
Note: I tried lerpColor function but didn't help me.
Math is the secret. Is often is.
There are a couple things you'll need to keep track of to accomplish this: the time it takes to cross the screen (you said 30 seconds), the speed of the sphere, the speed at which the color changes.
Before we start, I suggest that you use float for your variables which are positions and speeds. Integers will do the job, but at some point when you want precision you may regret not using floats or a similar type.
There are 2 ways to deal with changes over time: you can calculate time and draw what needs to be drawn where it's supposed to be, or calculate how many frames will be drawn in a certain amount of time and move things accordingly. The first technique has the advantage of being able to draw things where they are supposed to be even if the system is laggy (Processing will lower the framerate if it's not able to respect it), while the second is often easier to work with. We'll go with the framerate technique, as this is not supposed to be complicated and because most programs won't need so much resource that it'll lower the framerate.
The framerate, in Processing, is also the rate at which the main loop (the draw() loop) run. So we'll choose a framerate which will let us calculate the speed of the sphere and the speed at which the color change. The rest is just watching it move.
Here's your example, but modified so it works approximately as you told:
float speed;
float x, z = 50;
float greenBlueStrength = 0;
float colorFadeRate = 1;
int fadeTimeInFrames;
void setup() {
size(400, 400, P3D);
frameRate(60); // 60 is the default framerate per second
// so 30 seconds == (30*60) == 1800 frames
// so you must have the speed to match
fadeTimeInFrames = 60 * 30;
speed = (width - 50) / (float)fadeTimeInFrames;
colorFadeRate = 255 / (float)fadeTimeInFrames;
println(colorFadeRate);
}
void draw() {
background(0);
textSize(30);
text((millis()/1000) + " s. // color: " + (int)greenBlueStrength, 20, 50);
// this is just to keep track of changes while they happen
noStroke();
lights();
translate(x, height/2, z);
fill(255, greenBlueStrength, greenBlueStrength);
sphere(25);
if (x > width -50) {
noLoop();
} // no actual change, but use brackets anyway, it's easier to read
// updating what needs to be updated
x += speed;
greenBlueStrength += colorFadeRate;
}
I'll hang around so don't hesitate if you have questions.
Have fun!
I think something like that would work:
int r=255,b=255,g=255;
...
void draw(){
...
int percent=x/width*100;
fill(r,b*percent,g*percent)
sphere(25)
...
}
so the sphere would be red only on the left of the screen and white on the right

What's the best way to implement a color cycling background?

What's the best way to cycle the color of a background smoothly (as well as other things) using cos or sin in java, without using more than one file? I've tried using randomness and increasing each individual r, g, and b value separately to make this look kind of normal, but it's jittery, not smooth, and the colors are horrid. Right now, it's just plain white. I included only the necessary code, and I am using Processing 3.
//background
int bg1 = 255; //r
int bg2 = 255; //g
int bg3 = 255; //b
void draw() {
fill(bg1,bg2,bg3);
}
You've got the general idea down. It's a three-step process:
Step 1: Declare variables at the top of your sketch.
Step 2: Use those variables to draw your scene.
Step 3: Change those variables over time.
This is the basic approach to create any animation in Processing. Here is a tutorial with more information.
Here is a small example that shows a window that cycles between white and black:
float c = 0;
float cChange = 1;
void draw(){
background(c);
c += cChange;
if(c < 0 || c > 255){
cChange *= -1;
}
}
You would need to do something similar, but with 3 color values instead of 1. Note that I'm only changing the color by a small amount each time, which makes it appear smooth instead of jittery.
If you're still having trouble, please post an updated MCVE in a new question and we'll go from there. Good luck.
If you specifically want to use a sine wave as input rather than the sawtooth wave then you need to map your input (e.g. time) to some color range. For example:
every 2000 milliseconds value increases from 0 to 2.0
value ranges from -1 to 1.
the output of sin(value) ranges from -1 to 1.
map the output to a color range.
map() works well for mapping values, but you can also use colorMode() for mapping color ranges -- so rather than moving your sine output values around, just make your output 0-2.0 and set the max RGB or HSB value to 2.0 rather than 255.
Here are some examples, all running simultaneously in one sketch:
float val;
float out;
void draw() {
background(0);
val = TWO_PI * (millis()%2000)/2000.0; // every 2000 milliseconds value increases from 0 to 2PI
out = sin(val);
// white-black (256-0)
pushStyle();
fill(128 + 128*out);
rect(0,0,50,50);
popStyle();
// red-black (255-0)
pushStyle();
colorMode(RGB, 255);
fill(255*(out+1), 0, 0);
rect(50,0,50,50);
popStyle();
// hue rainbow (0-2)
pushStyle();
colorMode(HSB, 2.0);
fill(out+1, 2, 2);
rect(0,50,50,50);
popStyle();
// hue blue-green (3 to 5 / 9)
pushStyle();
colorMode(HSB, 9);
fill(out+4, 9, 9);
rect(50,50,50,50);
popStyle();
translate(width/2,height/2 - out * height/2);
ellipse(0,0,10,10);
}
Don't understand what you mean by cos and sin in relation to background color. But maybe something like this is what you want?
void draw(){
int H = frameCount%1536;
background(color(abs(H-765)-256,512-abs(H-512),512-abs(H-1024)));
}

Box2D move bodies at same rate regardless of FPS

Sorry, I couldn't word my title properly but I will explain my problem with more clarity here.
I am using libgdx.
When I want to move a Texture so that it covers the same distance with all FPS I will do this:
//...define Player class with x property up here.
Player player = new Player();
int SPEED = 100
public void render() {
player.x += SPEED * Gdx.graphics.getDeltaTime();
}
Now I want to know how to do this to have the same affect on a body in box2d. Here is an example(the render method of a class that extends ApplicationAdapter):
public void render() {
//clear screen, ... do other stuff up here.
playerBody.applyForce(new Vector2(0.5f / PIXEL_PER_METER, 0.0f), playerBody.getWorldCenter(), true);
//PIXEL_PER_METER -> applied to scale everything down
//update all bodies
world.step(1/60f, 6, 2);
}
This applies a force on the playerBody so that it's acceleration increases. How do I make shore, just like with my first example, that how fast the body is travelling stays constant across at 30fps, 10fps, 60fps, etc. I know the timeStep parameter of the world.step is the amount of time to simulate but this value shouldn't vary.
Thankyou in advance.
You can update all bodies with delta (not 1/60 fixed delta)
world.step(Gdx.graphics.getDeltaTime(), 6, 2);
EDIT:
As #Tenfour04 mentioned, in order to prevent high delta values (causes huge jumps), we mostly set a cap for delta.
world.step(Math.min(Gdx.graphics.getDeltaTime(), 0.15f), 6, 2);
I wouldn't use a variable timestep - this is the approach I've used:
private float time = 0;
private final float timestep = 1 / 60f;
public void updateMethod(float delta) {
for(time += delta; time >= timestep; time -= timestep)
world.step(timestep, 6, 2);
}
Basically a variable-ish timestep, but uniformly updating.
If you run your game at very low FPS, or if you force it to with the application configuration (e.g. for testing) this will keep updating at roughly the same speed as a normal 60 FPS instance.
Take a look at Fix your timestep!

LibGDX Path (CatmullRomSpline) Constant Speed

I’m trying to achieve constant speed on a path using the LibGDX CatmullRomSpline and I’m having problems getting it to work. I’ve tried researching on this topic a lot including reading the LibGDX wiki, but their explanation for achieving constant speed doesn’t really make sense and I wasn’t able to get their method to work. https://github.com/libgdx/libgdx/wiki/Path-interface-&-Splines
In my case, the derivative values are very large (in the hundreds) so when dividing a number between 0-1 by the derivative the result is very small and the movement is very slow and still not constant. So I’m not sure exactly how their example works.
In my example I have a couple visual aids coinciding with the speed of the ball, the bar at the bottom of the screen increases in length as the speed increases and the color also changes from white to red as the speed increases.
In the act() method of MyPath.java I have two sections commented out starting with [1] and [2]. The first one is normal with the variable speed through the path and the second one is my failed attempt at getting the LibGDX wiki constant speed to work. So just un-comment these lines to switch between the two versions.
My idea for constant speed involves figuring out the speed based on the total length of the path (using the approxLength(1000) method on the spline), then using the derivative function to determine the actual speed at a given instant, and adjusting the percentage value sent into the spline to compensate for the speed changes in order to make the speed constant. However, I don’t quite understand what the derivative function actually represents. I posted a question about the derivative function earlier, but based a comment I received I figured it might be easier to ask about achieving constant speed instead. Here is my previous question on the derivative function:
LibGDX CatmullRomSpline Derivative Meaning?
Any ideas on how to achieve constant speed in my example (or explaining what the derivative function for the CatmullRomSpline actually represents so I could better understand how to use it) would be greatly appreciated.
For anyone who'd like to run the program, here are the two image files I created for my example (add these to the root of the assets folder):
http://dropshots.com/Tekker/date/2015-09-19
Here is my example code:
DesktopLauncher.java: (changed desktop window width and height to 1000)
public class DesktopLauncher {
public static void main (String[] arg) {
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
config.width = 1000;
config.height = 1000;
new LwjglApplication(new TEST(), config);
}
}
TEST.java:
public class TEST extends Game {
Stage stage;
MyPath path;
#Override
public void create () {
stage = new Stage();
stage.setViewport(new ScreenViewport(stage.getViewport().getCamera()));
Gdx.input.setInputProcessor(stage);
path = new MyPath(1000, 1000);
stage.addActor(path);
}
#Override
public void render () {
Gdx.gl.glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.act(Gdx.graphics.getDeltaTime());
stage.draw();
}
#Override
public void dispose(){
stage.dispose();
super.dispose();
}
}
MyPath.java:
public class MyPath extends WidgetGroup {
Image start, end, path, bar1, horizontal;
float time, percent, dVal, pathLength, dMax=1000, cycle=6, maxPercent, deltaCycle;
CatmullRomSpline<Vector2> catmull;
Vector2 result = new Vector2();
Vector2 previousResult = new Vector2(50,150);
Vector2 derivative = new Vector2();
Vector2 previousDerivative = new Vector2();
Vector2[] points = {
new Vector2(50,150), new Vector2(50,150),
new Vector2(400,800), new Vector2(600,150), new Vector2(700,400),
new Vector2(860,150), new Vector2(860,150)
};
boolean print = true;
public MyPath(int width, int height){
this.setSize(width, height);
catmull = new CatmullRomSpline<Vector2>(points, false);
createPath();
createBar();
pathLength = catmull.approxLength(1000);
}
#Override
public void act(float delta){
// [1] VARIABLE SPEED
//time += delta;
//percent = (time / cycle) % 1;
// [2] CONSTANT SPEED FAIL!
//catmull.derivativeAt(previousDerivative, percent);
//time += delta;
//percent = ((time / cycle) / previousDerivative.len() ) % 1;
catmull.valueAt(result, percent);
path.setPosition(result.x, this.getHeight() - result.y);
updateSpeedVisuals();
debugPrint();
previousResult.set(result);
}
private void createPath(){
start = new Image(new Texture("dot.png"));
start.setColor(Color.GRAY);
start.setPosition(50, this.getHeight() - 150);
this.addActor(start);
end = new Image(new Texture("dot.png"));
end.setColor(Color.GRAY);
end.setPosition(860, this.getHeight() - 150);
this.addActor(end);
path = new Image(new Texture("dot.png"));
path.setColor(Color.WHITE);
this.addActor(path);
}
private void createBar(){
Texture texture = new Texture("ninepatch.png");
int crop = (int)(texture.getWidth()/2)-1;
NinePatch patch9 = new NinePatch(texture, crop, crop, crop, crop);
bar1 = new Image(patch9);
bar1.setColor(Color.GRAY);
bar1.setPosition(5, this.getHeight()-900);
this.addActor(bar1);
}
private void updateSpeedVisuals(){
catmull.derivativeAt(derivative, percent);
dVal = derivative.len() / dMax;
path.setColor(1f, 1f-dVal, 1f-dVal, 1f);
bar1.setWidth(derivative.len());
bar1.setColor(1f, 1f-dVal, 1f-dVal, 1f);
}
private void debugPrint(){
maxPercent = (percent > maxPercent) ? percent : maxPercent;
if (maxPercent > percent){
print = false;
}
if (print){
String debugPrint = "";
debugPrint = debugPrint + "pathLength=" + pathLength + "\t";
debugPrint = debugPrint + "derivative=" + derivative.len() + "\t";
System.out.println(debugPrint);
}
}
}
Since the derivative is the rate of change of the spline position it is indeed the 'speed', and when the spline is bending away from the underlying data points it has to 'speed up' to make the calculated spline reach the next data point in time, you must divide out this speed to perceive a visual constant speed.
You aren't getting a constant speed because you are still incrementing your time variable by delta instead of delta divided by the rate of change (derivative). You should be adding a variable amount to the percent variable each frame, instead you were modifying everything by the derivative of a single point along the Catmull-Rom spline.
Instead of:
catmull.derivativeAt(previousDerivative, percent);
time += delta;
percent = ((time / cycle) / previousDerivative.len() ) % 1;
You should:
catmull.derivativeAt(previousDerivative, percent);
percent += derivativeAverage / cycle * delta / previousDerivative.len();
percent %= 1;
you should use the average derivative divided by cycle now since you can't use cycle alone as a percent per second variable anymore.
Iterating over the spline to find the average value of the derivativeAverage:
int samples = 100; //the higher the more accurate, however slower
float derivativeAverage = 0;
Vector2 out = new Vector2();
for (float i=0;i<1;i+=1f/samples) {
catmull.derivativeAt(out, i);
derivativeAverage += out.len();
}
derivativeAverage /= samples;

Platforms in a class not moving when called in

For a university course I'm making a game with a friend. The general idea is that we have some platforms moving from right to left and each time one goes offscreen it is generated at a random x and y position on the right (within some limits). There will be a little sprite that jumps from platform to platform.
We have reached a problem we're not sure how to solve. We have all the right code and everything but the platforms just won't move. They should move to the left at a constant speed of -4 pixels per frame (rectVelocity).
We cannot get them to move, though; they are static on the screen at the position each one is initially called in at.
This is the code as condensed as I can make it:
Platforms [] mainPlats;
void setup() {
size(750, 400);
mainPlats = new Platforms[3];
}
void draw() {
level();
}
void level() {
//This is the code for the first platform
mainPlats[0] = new Platforms(200, 200, 100, 15); //These values need to be set inside the class so that
//they aren't constantly overwriting the movement variables in the class
mainPlats[0].displayPlat();
mainPlats[0].platTransition();
//This is the code for the second platform
mainPlats[1] = new Platforms(420, 300, 100, 15);
mainPlats[1].displayPlat();
mainPlats[1].platTransition();
//This is the code for the third platform
mainPlats[2] = new Platforms(570, 350, 100, 15);
mainPlats[2].displayPlat();
mainPlats[2].platTransition();
}
class Platforms {
PImage platform;
int rectX, rectY, rectWidth, rectHeight;
int rectVelocity = 4;
Platforms(int x, int y, int w, int h) {
rectX = x;
rectY = y;
// rectX = (int(random(600, 800))); //Tried to randomise start position, failed hilariously
//rectY = (int(random(150, 350)));
rectWidth = w;
rectHeight = h;
}
void displayPlat() {
platform = loadImage ("images/tiles.png");
//imageMode(CENTER);
image(platform, rectX, rectY, 100, 15); //rectangle platforms replaced with images
}
void platMove() {
rectX -= rectVelocity;
}
void platTransition() {
if (rectX < -200) {
rectX = (int(random(700, 1000)));
rectY = (int(random(150, 350)));
}
}
}
From the draw() function, you call your level() function, which initializes your Platform array every single frame.
This means that you create new Platforms at their starting positions every frame. You never see the platforms move, because as soon as you do move them, you replace them with new platforms at the starting positions again.
So step one is to move their initialization out of the level() function and only call them once, at the beginning of your sketch- the setup() function would be one place you could put them.
Your other problem is that you never actually call the platMove() function. So step two is to make sure you call that function.
A solution might look something like this:
Platforms [] mainPlats;
void setup() {
size(750, 400);
mainPlats = new Platforms[3];
mainPlats[0] = new Platforms(200, 200, 100, 15);
mainPlats[1] = new Platforms(420, 300, 100, 15);
mainPlats[2] = new Platforms(570, 350, 100, 15);
}
void draw() {
level();
}
void level() {
mainPlats[0].displayPlat();
mainPlats[0].platMove();
mainPlats[0].platTransition();
mainPlats[1].displayPlat();
mainPlats[1].platMove();
mainPlats[1].platTransition();
mainPlats[2].displayPlat();
mainPlats[2].platMove();
mainPlats[2].platTransition();
}
Also note that you shouldn't load the image every single frame, either. You should only load it once, at startup. You also might want to use a for loop to iterate over your Platforms instead of referring to every single index. But these don't really affect your problem.
You've got rectX as positive values (>0) when you construct the platforms, but you are checking for rectX < -200 when you call platTransition, which is why it never does anything.

Categories