I Added the coins on the track of user by creating a Sprite, which i kept in a Body. The problem is when the player collide with coin, the coin removed but it takes a jerk for nano second. I want the player to run smooth even when he collides with the coin.
You are correct, the problem is due to Box2D. Obviously, removing a body takes some time and causes some delay. If you don't plan to have a very large number of bodies you can just keep them the whole time, you can attach a sensor to the body. Sensor is a special kind of fixture that does not cause collisions with other bodies but you can find out whether the bodies are touching. This way you could keep the coins in their place and only remove the Sprite so that the coin will disappear without the overhead caused by removing a body.
See the Box2d manual here:
http://www.box2d.org/manual.html#_Toc258082972
Another thing is collision filtering, although I am not certain whether the isTouching() method would return true if the collision bits are set up appropriately, so you'll have to try that. There is a nice tutorial here:
http://www.iforce2d.net/b2dtut/collision-filtering
Related
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.
I need to generate objects for my little character to jump over. I have the artwork for these obsticles and my character can jump and I have a scrolling background.
How can I spawn my artwork for my obsticles on my x axis with spacing inbetween them?
Can anyone provide me with some sample code or atleast try and point me in the right direction?
Many Thanks,
James
Yes. You can. You want to use some sort of loop that generates them:
2 options you can use:
local function frameHandler()
if should_I_make_object() then
createObstacle()
end
end
Runtime:addEventListener("enterFrame", frameHandler)
this approach will create new objects according to frame rate. IE, lets
you create objects every 100 frames lets say. This will make levels play the
same (have the same number of obstacles) on different devices that have varied frame-rate
Option 2:
local function createObstacle()
--your_create_obstacle_code()
if game_is_still_playing() then
timer.performWithDelay(object_spawn_delay, createObstacle)
end
end
This option will create a new object every object_spawn_delay milliseconds.
This is easy to code, and is a nice solution when you need things to happen on
a time-dependent interval. But you do need code to decide if the game is still playing.
Also, be aware that if the game ends, there might still be a lingering callback to
createObstacle() that can create nasty bugs. Make sure to do proper cleanup when
the level / game ends and be aware this callback may be an issue.
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.
I have a Fast Moving Body(A) which is dynamic. It is supposed to collide with another Body(B). A collides with B, but sometimes it passes the Body B without collision. This is totally random behavior. I must have that collision. Kindly guide why it is acting like this, randomly.
The effect of one object passing through another due to large movement in a single timestep is called tunneling.
Box2D uses Continuous Collision Detection between dynamic and static objects to solve this problem. However, your case (dynamic v.s. dynamic) isn't automatically handled, so it's just a random dice throw whether your objects happen to be in colliding positions at the exact moment the collisions are evaluated.
From the Box2d Manual:
Normally CCD is not used between dynamic bodies. This is done to keep
performance reasonable. In some game scenarios you need dynamic bodies
to use CCD. For example, you may want to shoot a high speed bullet at
a stack of dynamic bricks. Without CCD, the bullet might tunnel
through the bricks.
Fast moving objects in Box2D can be labeled as bullets. Bullets will
perform CCD with both static and dynamic bodies. You should decide
what bodies should be bullets based on your game design. If you decide
a body should be treated as a bullet, use the following setting.
bodyDef.bullet = true;
The bullet flag only affects dynamic bodies.
Box2D performs continuous collision sequentially, so bullets may miss
fast moving bodies.
I am developing a 2D, underwater, action-RPG for Android, using Box2D as the physics engine, mainly for collision detection, collision response and movement of in-game characters within an environment comprised of walls, rocks, and other creatures.
I have tried two different approaches for implementing character animations using Box2D, and have found issues with both. As I'm new to Box2D and physics engines, I would appreciate a recommendation on how these things should best be done.
An example of an animation I am trying to do is as follows:
A fish wants to attack another fish, so does the following:
1) Move towards target at speed
2) Take a bite out of target creature
3) Turn and flee, back to where the attack began
4) Turn back to face the target, ready for another attack
The two approaches I've tried are:
A) Apply a force to the attacker (using body.applyForce() ) to move it towards the target, then another force to move it back again, after the collision
Problems:
* Frequently the attacker hits the target and bounces off and goes hurtling back at great speed, and bounces off walls, everywhere. The speed is pretty random, depending on where it impacts the target, the mass of the target, etc. It breaks the animation and looks terrible.
* It's very hard to figure out what forces should be applied to the attacker and when, to simulate a particular animation in a physics world so it looks realistic
B) Directly set the position of the attacker (using body.setTransform() ) to move the attacker to the correct position, as it moves forwards each step, then moves back again.
Problems:
* Directly setting the position allows the attacker to ignore collisions with walls and other creatures, so getting stuck in a wall is common
* If the player is attacking, I update the world origin as the player moves, to keep the player mid-screen. This works well, except when I start an animation, as I don't want the screen to follow the animation, but only the movement component of the existing velocity, which I don't know, as I'm overriding the Box2D forces/velocities when I set the position. It's possible to do this I'm sure, but difficult - maybe I'm missing something obvious.
Should I be monitoring the collisions? Overriding the collision response?? Something else?
So, how would you recommend I approach this problem?
I'm only used to work with Farseer, but Farseer is a pretty direct port from Box2D, so I hope this answer is still helpful.
Next to applying force and teleporting you can also set the linear movement speed of a body. This way you can have the fish move towards the player without applying force. You should capture the collision events from the fish body and compare in each event if the fish has hit the player, then set false/NoCollision in the collision event with the player so that it doesn't bounce of. Now set the fish body to ignore any collisions with the player body and use a fixed joint to stick the fish to the player. You can now play your bite animation.
After the bite animation you want to disengage the fish. Start your flee animation, remove the joint and teleport the fish to the edge of the player body (so that it's not colliding with it). After that re-enable collisions between the fish and the player body and send the fish away from the player (either by setting linear movement speed again, or for a nice bounce effect via force.