How to implement movement speed of object correctly? - android

So I am coing an android game and have managed to make a ball roll over the screen in the direction you tilt your phone. However I would like to make the ball roll faster the more you tilt your screen.
But what is the best way to implement this? Taking bigger steps is obv not good, it makes collisions hard to calculate. I want to move more steps per second instead.
So lets say you have a tiled board and you implement speed as tiles/millisecond. But that is problematic also speed will not be continous. You'd perhaps move 1 step every 10th time in a loop instead of every time in the loop. So you would move, then be still, then move, etc instead of continously moving. But maybe that is as good as it gets?
So this problem applies generally for any kind if computer graphics I guess. How do you implement this the best way? I'm specifically interested in what applies to Android.

The natural way of implementing speed and position problems is to have position calculated with the speed that way :
position = speed * dt
with dt constant, adapted for your implementation.
So basically the natural way is to increase the step. You say it's obviously bad for collision detection but with a limited speed and a small dt I don't really see why.

Related

Preventing body from too high acceleration

I am currently creating an Andengine game which features a ball and a blocker just like pong, except in my game the world and blocker aren't squares and are instead circles.
Right now when the ball bounces off of the blocker all physics seem to check out alright but when I move the blocker really fast to the destination and the blocker hits the ball the ball goes flying off the screen at insane speeds.
How would I go about keeping the ball's velocity at the same speed all the time while keeping current physics?
Don't remember exact code but the logic is:
in onManageedUpdate check the speed of your object, then if speed exceed some value you are happy with set the linear speed to this good value.
Other solution could be that you use ContactListener and in postSolve or endContact you set velocity to desired one.
Also check why this speed after bounce is that fast. Is it because a blocker is moving really fast? Does it also happen when blocker is moving slowly?

Continuous gesture recognizion with DTW

I try to use Dynamic Time Warping (DTW) to detect gestures performed with a smartphone by using the accelerometer sensor. I already implemented a simple DTW-algorithm.
So basicly I am comparing arrays of accelerometer-data (x,y,z) with DTW. The one array contains my predefiend gesture, the other should contain the measured values. My problem is, that the accelerometer-sensor measures continously new values and I don't know when to start the comparison with my predefined value-sequence.
I would need to know when the gesture starts and when it ends, but this might be different with different gestures. In my case all supported gestures start and end at the same point, but as far as I know I can't calculate the traveled distance from acceleration reliably.
So to sum things up: How would you determine the right time to compare my arrays using DTW?
Thanks in advance!
The answer is, you compare your predefined gesture to EVERY
subsequence.
You can do this in much faster than real time (see [a]).
You need to z-normalize EVERY subsequence, and z-normalize your predefined gesture.
So, by analogy, if you stream was.....
NOW IS THE WINTER OF OUR DISCONTENT, MADE GLORIOUS SUMMER..
And your predefined word was made, you can compare with every marked word beginning (denoted by white space)
DTW(MADE,NOW)
DTW(MADE,IS)
DTW(MADE,THE)
DTW(MADE,WINTER)
etc
In your case, you don’t have makers, you have this...
NOWISTHEWINTEROFOURDISCONTENTMADEGLORIOUSSUMMER..
So you just test every offset
DTW(MADE,NOWI)
DTW(MADE, OWIS)
DTW(MADE, WIST)
DTW(MADE, ISTH)
::
DTW(MADE, TMAD)
DTW(MADE, MADE) // Success!
eamonn
[a] https://www.youtube.com/watch?v=d_qLzMMuVQg
You want to apply DTW not only to a time-series, but to a continously evolving stream. Therefore you will have to use a sliding window of n recent data points.
This is exactly, what eamonn described in his second example. His target pattern consists of 4 events (M,A,D,E) and therefore he uses a sliding window with length of 4.
Yet in this case, he makes the assumption, that the data stream contains no distortions, such as (M,A,A,D,E). The advantage of DTW is that it allows these kind of distortions and yet recognizes the distorted target pattern as a match. In your case, distortions in time are likely to happen. I assume that you want equal gestures performed either slow or fast as the same gesture.
Thus, the length of the sliding window must be higher than the length of the target pattern (to be able to detect a slow target gesture). This is computationally expensive.
Finally, my point is: I want to recommed you this paper
Spring algorithm by Sakurai, Faloutsos and Yamamuro.
They optimized the DTW algorithm for datastreams. You will no longer need more than n*n computations per incoming event but only n. It basically is DTW but cutting down all unneccesary computations and only taking the best possible alignment of the template onto the stream into account.
p.s. most of what I know about time-series and pattern matching, I learned by reading what Eamonn Keogh provided. Thanks a lot, Mr. Keogh.

Android: Achieving smooth roll of ball using accelerometer

I have developed a maze game for Android where you control the ball by tilting the phone.
So I use the accelerometer and integrate the x and y accelerometer values and then move the ball a step in that direction.
I have a problem though, I cannot achieve a very smooth roll. When the ball picks up speed it is to obvious that it jumps in big discrete steps. I have seen other apps like this where the ball rolls fast but smoothly.
So I might have to change my strategy, use some sort of time solution instead. Now the faster the speed the bigger the step I move. Instead maybe I should have a timer that moves the ball 1 pixel every ms if speed is high or only every 10th ms if the speed is low or something along those lines.
Or how do people achieve a smoother roll?
Also: Would you use OpenGL for this?
What you're really doing here is integrating coupled differential equations. Don't worry if you haven't taken enough calculus or physics to know what that means.
People who integrate coupled differential equations for a living have evolved many algorithms to do so efficiently.
You really have four equations here: acceleration in x- and y-directions and velocity in x- and y-directions:
dvx/dt = ax
dvy/dt = ax
dsx/dt = vx
dxy/dt = vy
(sx, sy) give the position of the ball at a given time. You'll need initial conditions for (sx, sy) and (vx, vy).
It sounds like you've chosen the simplest way to integration ODEs: Euler explicit integration. You calculate the values at the end of a step from the values at the beginning plus the rate of change times the time step:
(vx, vy)_1 = (vx, vy)_0 + (ax, ay)_0 * dt
(sx, sy)_1 = (sx, sy)_0 + (vx, vy)_0 * dt
It's easy to program, but it tends to suffer from stability problems under certain conditions if your time step is too large.
You can shrink your time step, which will force you to perform the calculations many more times, or switch to another integration scheme. Search for implicit integration, Runge-Kutta, etc.
Integration and rendering are separate problems.

Motion detection using OpenCV

I see queries related to opencv motion detection, but my requirement is much simpler , so i am asking the question again .
I would like to analyse video frames and see if something has changed in the frame. Any kind of motion occurring in the frame has be recognized. I just want to get notified if something happens. I don't need to track/ draw contours.
Attempts made :
1) Template matching using OpenCV ( TM_CCORR_NORMED ).
I get the similarity index using cvMinMaxLoc &
if( sim_index > threshold )
"Nothing chnged"
else
"Changed
Problem faced :
I couldn't find a way to decide on how to set thresholds. The values of false match and perfect were very close.
2) Method 2
a) Make running average
b) Take abs difference between current frame and moving average.
c) Threshold it and made it binary
d) Count the number of non zero values
Again am stuck with how to threshold it, because i am getting a large number of non zero values even for very similar frames.
Please advice me on what approach i should take. Am i going in the right direction with the above two methods, or is there a simple method which can work in all most generic scenarios.
Method 2 is generally regarded as the most simple method for motion detection, and is very effective if you have no water, swaying trees or highly variable lighting conditions in your video.
Normally you implement it like this:
motion_frame=abs(newframe-running_avg);
running_avg=(1-alpha)*running_avg+alpha*newframe;
You can threshold the motion_frame if you want, then count the nonzeroes. But you could also just sum the elements of the motion_frame and threshold that instead (be sure to work with floating point numbers). Optimizing the parameters for this is pretty easy, just make two trackbars and play around with it. Typically alpha is around [0.1; 0.3].
Lastly, it is probably overkill to do this on entire frames, you could just use subsampled versions and the result will be very similar.

Is there a faster algorithm for collision detection?

I'm writing this game on Android where I have a bunch of characters moving around who collide with each other. Everything works fine but when I get passed a certain number of characters on the screen at the same time, the performance of the app gets hit severely. I did my tests and drawing is not causing the low frame rate, it is the algorithm for collision detection, since every time they move they have to check their location to all the other characters. So currently I'm just looping through them all for each character. Is there a way to improve on this? Is there a performance trick to collision detection on a big number of objects that I don't know about?
Yes, there is a technique based on a first broad-phase and second narrow-phase colission detection.
I'll quote some paragraps from: Beginning Android Games, by Mario Zechner.
Broad phase: In this phase we try to figure out which objects can
potentially collide. Imagine having 100 objects that could each
collide with each other. We’d need to perform 100 * 100 / 2 overlap
tests if we chose to naively test each object against each other
object. This naive overlap testing approach is of O(n^2) asymptotic
complexity, meaning it would take n^2 steps to complete (it actually
finished in half that many steps, but the asymptotic complexity
leaves out any constants). In a good, non-brute-force broad phase, we
try to figure out which pairs of objects are actually in danger of
colliding. Other pairs (e .g., two objects that are too far apart for
a collision to happen) will not be checked . We can reduce the
computational load this way, as narrow-phase testing is usually pretty
expensive.
Narrow phase: Once we know which pairs of objects can potentially
collide, we test whether they really collide or not by doi ng an
overlap test of their bounding shapes.
The broad phase involves dividing the world in large cells, making some sort of grid.
Each cell has the exact same size, and the whole world is covered in cells. If two objects are not in the same cell, a narrow phase for those two objects is not needed.
Quote once again:
All we need to do is the following:
Update all objects in the world based on our physics and controller step.
Update the position of each bounding shape of each object according to the object’s position. We can of course also include the orientation and scale as well here.
Figure out which cell or cells each object is contained in based on its bounding shape, and add it to the list of objects contained in those cells.
Check for collisions, but only between object pairs that can collide (e.g., Goombas don’t collide with other Goombas) and are in the same cell.
This is called a spatial hash grid broad phase, and it is very easy to implement. The first thing we have to define is the size of each cell. This is highly dependent on the scale and units we use for our game’s world.
It also depends on the bounding shape you're using. A simple rectangle or circle around the characters and it's euclidean distance is one simple thing to calculate, but a finer shape (including details as "the head", "the legs" with little additional bounding shapes) will be more a lot more computationally expensive to calculate.
If all objects are free to move to any part of the screen, then the best you can do is your O(n^2) algorithm. You can improve it by a constant factor by realizing that when you check if object A collides with object B, then you don't have to later check if object B collides with object A.
enclose each character within a fixed size square. Before you check for character collision, check if the squares in which they are enclosed collide. If and only if the squares collide, there would be a chance for the characters to collide. Now checking for squares collision is easy as you have to just compare the x & y co-ordinates.
Dividing into a broad phase and narrow phase as Federico suggests only helps if your collision detection algorithm is expensive, i.e. it's not a simple bounding box.
Fortunately there are other options.
You could try a collision mask technique. Since you don't seem to be limited by rendering speed, render a bounding box for each object into a hidden bitmap. Before rendering the next object, check the pixels at the four corners of its bounding box to see if they have already been written. You can even use a different colour for each object so that the colour tells you which object the collision was with.
Another popular trick is to simply not do every collision check every frame. For example, games like Super Mario Bros actually only check for collisions between the player and enemies every other frame. You can do a more advanced version where you check all objects in a round-robin fashion, doing as many as it can per frame. When things get busy each object might only be checked every other or even every third frame, but the player is unlikely to notice. This works best if your objects are not moving so fast that they can pass through each other one only one frame of collision.

Categories

Resources