Moving an object unaffected by FPS - java

Hello I am currently trying to move objects in my libgdx android application. The main issue is that i can't move my objects unaffected by the fps. Up to now i was using the delta time like this:
public void move(float delta){
this.setX(this.getX() + this.speed.x * delta); //moving just along x axis to keep it simple
this.speed.x += 1 * delta //some acceleration;
}
The move method is called on each frame. Imagine I have two devices, one with 1fps and one with 2fps, and now we move a object for 1 second with a start speed of zero. The object wouldn't have moved on the first device while it would have on the second one.
To sum up if the fps is increased the object moves slightly faster.
Up to now this little differnce was no problem but in this case it is important that the object moves 100% synchronous, because i want to measure the time the objects needs to reach some point.
So what is the right way to go here?

Actually... the way you are moving your objects when multiplying it by delta makes it FPS independent already :) Let see below graphic to understand it better:
open the picture in full size!
Atlhough you are adding some value to x twice per second when having 2FPS the value is twice smaller than when having 1FPS what means that in the every integer point of time the x of the object will be the same.
The situation you are afraid of would be true if you wouldn't multiply it by delta - then every second you would add the same value twice when having 2FPS than when having 1FPS - it means that after one second the object would be twice far more when having 2FPS than when having 1FPS.
Only thing affect by the FPS is rendering smoothness - but if you are refreshing the screen twice times more it is obvious that it will be more smooth.
By the way - if you are using Scene2D and looking for some other ways to move object look at Actions especially MoveToAction. Take a look at this tutorial to get some information.

Thanks to m.antkowicz provided informations i could do some better research and found some interesting artices. According to my current knowlege it is pretty hard move objects with dynamic accelleration based on the deltatime. The right way to go is to use fixed time stamps.

Related

How to reset coordinate if crosses float limits in an infinite running game in libgdx

I am new to the world of libgdx, I am developing an infinite running game. I am curious to know if a player is running for several hours and its position keeps on changing lets says its x value is increasing countinously, then what happens if position crosses float max limits. Some of the discussion suggests that we need to reset the coordinates after certain moments of time http://answers.unity3d.com/questions/491411/best-practices-for-endless-runner-type-games.html. But I am not sure how to achieve this in libgdx.
Whatever method you have of keeping the level "infinite" (without actually using up "infinite" memory), is where you can tie in "resetting" your character and level's position most conveniently.
In many cases, your character doesn't even need to "actually" be moving - the level can just be moving past him to the left.. similar to how people use a treadmill to run, but actually they stay in place. Destroy the pieces that move off-screen to the left and keep them coming on the right.
Alternatively, the character might be running along and at some convenient point you can move the entire level and the character back to the origin with nobody the wiser. It just has to happen "all at once", without physics methods of movements, and for every position you store. On slower devices, depending on the number of objects you have to move, this could result in a long single frame of lag... so use with caution.

How do I force two Box2D bodies to avoid colliding when they spawn on top of each other?

I'm in the process of creating a sidescrolling action game where you play a wizard that can cast spells. The spells are Box2D bodies that start in the middle of your player (who is also a Box2D body) and go outward in the direction you clicked on the screen.
I have all the collision detection working to where the spells you cast don't collide with each other and they don't collide with you. This works more-or-less flawlessly -- except for one instance. The first spell I cast creates a collision with the player that causes a brief period of physical knockback. The spell's path is not affected otherwise, and I don't notice a major change in the player's position. The only reason I know there is knockback at all is because the camera I have following the player suddenly shakes in that instant (and I've gone through the contact listener to verify that these particular bodies are forming a contact).
This is not the case for subsequent spells that are spawned from the same position, and it doesn't seem to be a problem that is related to the player's move speed or the projectile's cast angle. It may have something to do with how Box2D initializes items, but I couldn't promise that.
Does anyone know how I could fix this?
As weston mentioned, some more code may be needed, but it does sound odd that "the first spell" does this, but subsequent spawnings don't. Do you reuse bodies for subsequent spawns?
In box2d if you create 2 bodies that occupy the same space they will "knockback" from each other so that they DON'T occupy the same space. This is by design, and only happens on creation. I'm sure this is what you're seeing. Why it doesn't happen "afterwards" may be dependent on your code.
Ways around this might be to set some of your fixtures as sensors for a bit (collisions are ignored), or when you create a body, set active=false (again, collisions ignored). By "for a bit" I mean you may have to write some code to move your spell, ignoring collisions, until your spell has "cleared" your wizard. Then remove the sensor or make it active so collisions are back in play.
But that may be overkill, figuring out the subtlety of subsequent "spans" vs. your first one may be a better use of effort.
I managed to figure out where the problem was and how to solve it, but I wasn't able to fight out why it was happening.
I was using an OrthographicCamera to lerp to my player's position.
position.x += (universe.entity_handler.player.parts[0].body.getPosition().x - position.x) * Gdx.graphics.getDeltaTime() *
position.y += (universe.entity_handler.player.parts[0].body.getPosition().y - position.y) * Gdx.graphics.getDeltaTime() * LERP + zoom * viewportHeight / WORLD_PLAYER_Y_SKEW;
And when I fixed this by removing all lerping, the jitter was gone.
position.x = universe.entity_handler.player.parts[0].body.getPosition().x;
position.y = universe.entity_handler.player.parts[0].body.getPosition().y;
I have zero idea why linear interpolation was causing spastic movements like that, but hey - I got it to work. Maybe I'll go back and revisit the problem later.

X-Y Co-Ordinates input on slow fling are more but less on fast fling

I m working on a android app, which takes X-Y co-ordinates as input using openGL. The Problem is when we draw slow (fling slow) the input co-ordinate points are more and input co-ordinate points are less on fast fling.
I would like to know to the reason why it happens, So as to optimize and have same number of co-ordinates on touch with any speed/motion.
Since stackoverflow requires 10 reputation i could not upload images.. pls see the links below for images
fast moment : https://www.dropbox.com/s/rvdlz79mr2iowtx/fast_moment.png?dl=0
slow moment : https://www.dropbox.com/s/n2px7wcjw62wfi8/slow_moment.png?dl=0
The reason for this is how touch events are working. Your touch screen may report new touch coordinates but your system needs to collect those data which generally happens every X milliseconds. This results in getting N points per second rather then N points per distance made.
If you wish to have a relatively same amount of points per distance you should do a bit of an extra processing on the points you get. To begin with when the press is dragged you should always remember the last point received and when a new one comes you should compute the distance from the last one and if the distance is not long enough simply discard the point.
Note that this is only a first step but some more might need to be introduced so I suggest you create some class that will handle this for you and report to your target system.
So the first issue with this system you will most likely introduce is you will lose the last point sometimes because it might be too close to the one before it, so you need to handle the last point specifically.
Then if the drag was too fast you might find yourself having too little points in which case you should use some interpolation. It might be enough to simply interpolate lineally (an average of two points) but generally you would want to create a nice curve interpolated between at least 3 points to get a nice curve.
So what I suggest in general is to create a trace class that will hold all the points you receive from touch events (until the finger is lifted). Then on every point received you should analytically generate the new array of points from the ones gotten by the events and report them to the target system.

J2ME game thread

I'm trying to make a game for J2ME something like the game Zuma, the structure of classes that you need to know is as follow :
-Level class which holds info about a level such as a vector of points (class I made called Point, the path that the balls will follow), vector of balls (class I made called Ball) to hold different balls object, speed (the speed of the balls in that specific level).. (There're more fields but nothing that you need to worry about)
-Frog class (just so you'd know it exists) if you're not familiar wit the game zuma it serves as a controllable turret that can shoot balls.). (No need to worry about the fields in that class)
-MyGameCanvas which obviously extends GameCanvas and implement runnable, holds instance of frog and a level (the currently played level).. (There're more fields but nothing that you need to worry about). The run method serve as a listener for user input if user pressed right rotate the frog (essentially a sprite) by X amount if pressed left rotate by -X amount, pressed OK shoot a ball. Beside taking care of input the thread calls a render method which renders what going on, on the screen and updates balls position from the balls vector (by using the current level instance) using the vector of points (from the level instance aswell), now the problem is that I wanted each level to have different speed, by speed I mean that balls will "roll" (=move) on screen slower, so I can do it with just using the speed value in the Thread.sleep method and increase the sleep time because the run method is taking input from user making the frog movements and input reaction to be slowed down aswell, I thought maybe doing each ball a seperate thread but thats not really good in my opinion because there'll be alot of threads + when I update each ball location on the screen I actually use the WHOLE ball vector from the level instance for things like if a ball need to gove backwards if there's a gap between the ball and the one behind him, or when to render the ball depending if the ball after him is already rendered and on the "track" (the points vector), so I don't really know how I should do it, any advices guidance would be highly appriciated ! Thanks in advance and hopefully you could understand what I wrote.. Also I don't think I need to give code examples really because I don't wanna use what I want to CHANGE what I wrote so it wouldn't really help providing the run/render methods, all you need to know is the structure of the classes I gave you and the fields they have that I told you about.
Various developers use various methods for controlling the speed of sprite-movement.
JavaME is one of the many platforms that requires you to also consider different resolutions and CPU speed. So it's never as simple as just incrementing the x value 1 pixel in each cycle of the main game loop.
Assuming 2 devices with different screen resolution, but otherwise running the same speed. Incremending x value by 1 in the cycle of the game loop, would obviously result in the sprite reaching the end of the screen faster on the small resolution.
Assuming 2 device with the same screen resolkution, but with different CPU's. Incrementing x value by 1 in the cycle of the game loop, would obviously result in the sprite reaching the end of the screen faster on the device with the fastest CPU.
Here is one way of working around that:
Create a variable, call it itemWait (where "item" is the name of the object you want to control the speed for).
The itemWait variable holds a value that tells the game loop how long should pass before next movement.
For example, say that the sprite should wait 40 milliseconds for each pixel it moves. The code would look somewhat like this:
// Variables defined outside the game loop
long lastTime, thisTime;
int cyclems;
int itemTime; // Replace "item" with the name of the object, like e.g. ballTime.
int itemWait = 40; // Wait 40 ms for each movement
int itemPixelsToMove = 1;
while (running == true) { // Game loop
lastTime = thisTime; // Set lastTime to the time-stamp of the previous cycle
thisTime = System.currentTimeMillis(); // Get the current time-stamp
cyclems = (int) (thisTime - lastTime); // How long did it take to execute previous loop
itemTime += cyclems; // How long has passed since last move
while (itemTime > itemWait) { // If it's time to move
itemTime -= itemWait;
moveItem(itemPixelsToMove);
}
// Do other game logic
// Draw everything
// Handle input, unless you handle it with keyPressed()
}
Using that method, the code doesn't care how fast the device is. And if you want to port the game to a different screen resolution, you can simply change either itemPixelsToMove or itemWait.
For example, say you set itemWait = 40; for 240x320 resolutions. Then you would set it to 40/240*480 = 80 for 480x640 resolutions. (This requires of course, that you also scale the graphics).
We've used this approach in www.PirateDiamonds.com - in case you're curious. The same code runs on whatever screen resolution you want.

Detecting Singularities in a Graph

I am creating a graphing calculator in Java as a project for my programming class. There are two main components to this calculator: the graph itself, which draws the line(s), and the equation evaluator, which takes in an equation as a String and... well, evaluates it.
To create the line, I create a Path2D.Double instance, and loop through the points on the line. To do this, I calculate as many points as the graph is wide (e.g. if the graph itself is 500px wide, I calculate 500 points), and then scale it to the window of the graph.
Now, this works perfectly for most any line. However, it does not when dealing with singularities.
If, when calculating points, the graph encounters a domain error (such as 1/0), the graph closes the shape in the Path2D.Double instance and starts a new line, so that the line looks mathematically correct. Example:
(source: imagesocket.com)
However, because of the way it scales, sometimes it is rendered correctly, sometimes it isn't. When it isn't, the actual asymptotic line is shown, because within those 500 points, it skipped over x = 2.0 in the equation 1 / (x-2), and only did x = 1.98 and x = 2.04, which are perfectly valid in that equation. Example:
(source: imagesocket.com)
In that case, I increased the window on the left and right one unit each.
My question is: Is there a way to deal with singularities using this method of scaling so that the resulting line looks mathematically correct?
I myself have thought of implementing a binary search-esque method, where, if it finds that it calculates one point, and then the next point is wildly far away from the last point, it searches in between those points for a domain error. I had trouble figuring out how to make it work in practice, however.
Thank you for any help you may give!
You could use interval arithmetic ( http://en.wikipedia.org/wiki/Interval_arithmetic ) and calculate the interval of the function on each interval [x(i), x(i+1)]. If the resulting interval is infinite, skip that line segment. Speed-wise this should only be a couple times slower than just evaluating the function.
I think you are mostly on the right track.
I don't think figure 2 is mathematically incorrect.
For bonus points, you should have a routine which checks the diff between two consecutive values y1 & y2, and if it is greater than a threshold, inserts more points between y1 and y2, until no diff is greater than the threshold. If this iterative rountine is unable to get out of the while loop after 10 iterations or so, then that indicates presence of a singularity, and you can remove the plot between y1 and y2. That will give you figure 1.
If morpehus's solution is too slow for you, you can consider all the absolute values of jumps between two consecutive function values, and try to identifies large outliers -- these will be the infinite jumps.
If you decide to try this, and need help, leave a comment here.
I finally figured out a way to have singularities graphed properly.
Essentially what I do is for every point on the graph, I check to see if it is inside the visible graphing clip. If I hit a point on the graph that is outside the visible clip, I graph that first point outside the clip, and then stop graphing any invisible points after that.
I keep calculating points and checking if they are inside the visible clip, not graphing ones that are outside the clip. Once I hit a point that is inside the clip again, I graph the point before that point, and then graph the current point.
I keep doing this until I've graphed the entire line. This creates the illusion that the entire line is begin drawn, when only the visible parts are.
This won't work if the window is large and the actual graph size in pixels is small, but it does suffice for me.

Categories

Resources