cocos2d V3 PhysicsCollision body fall into another - cocos2d-iphone

I make two CCNodes, use cocos2d v3.
The node A is static physics, node B is dynamic.
And B's anchorPoint is ccp(0,0)
when B falls down and collisions with A , I found b's position.y is lower than A's position.y
It seems to be caught in the middle in a very short moment.
How can it does not fall into one, but also can meet the physical effect in normal collision?

The short answer is that you can not do that. Collision detection is defined in CS as the intersection of objects. Wikipedia
Collision detection is a tricky problem with complex objects, so best to stick with Chipmunk to handle that for you.
Physics calculations run in an "update loop" kind of fashion.
You can tweak you CCPhysicsNode with the following properties.
/**
* The number of solver iterations the underlying physics engine should run.
* This allows you to tune the performance and quality of the physics.
* Low numbers will improve performance, but make the physics spongy or rubbery.
* High numbers will use more CPU time, but make the physics look more solid.
* The default value is 10.
*/
#property(nonatomic, assign) int iterations;
/**
* Physics bodies fall asleep when a group of them move slowly for longer than the threshold.
* Sleeping bodies use minimal CPU resources and wake automatically when a collision happens.
* Defaults to 0.5 seconds.
*/
#property(nonatomic, assign) CCTime sleepTimeThreshold;
I think you should check out the graph of SpriteKit to get a general idea of how the update loop and physics simulation happen in these sorts of systems.
https://developer.apple.com/library/ios/documentation/GraphicsAnimation/Conceptual/SpriteKit_PG/Introduction/Introduction.html

Related

3D Rigid body sphere collision response (C++)

I am currently programming a 3D physics engine in C++ and have two spheres in my scene. I can detect when said spheres are colliding and they have some basic collision as a response but the spheres go inside each other a lot and act minimally upon each other so I'm looking to change this to be a RigidBody collision. I've looked online and many tutorials are on 2D collisions and use Elastic collision which is already hard enough to translate into 2D. Any advice on where to look for Rigidbody sphere collision would be a huge help and I'll put below the code I am currently using for my collision. Thanks in advance!
for (size_t i = 0; i < pool.size(); i++)
{
if (pool.at(i) == this)
{
continue;
}
DynamicObjects* other = pool.at(i);
SScollision = PFG::SphereToSphereCollision(pos, other->GetPosition(), rad, other->GetRadious(), contactPoint);
if (SScollision)
{
glm::vec3 relativeVel = this->GetVelocity() - other->GetVelocity();
float eCof = -(1.0f + 1.0f) * glm::dot(relativeVel, contactPoint);
float jLin = eCof / (1.0f / this->GetMass() + 1.0f / other->GetMass());
glm::vec3 collision_impulse_force = jLin * contactPoint / deltaTs;
//ClearForces();
AddForce(1.0f / this->GetMass() * collision_impulse_force);
//pool.at(otherI)->ClearForces();
other->AddForce(-(1.0f / other->GetMass() * collision_impulse_force));
}
}
When dealing with forces (as opposed to pressure, stress, or potentials), you will need to use a mass-spring-damper model. You can look into the discrete particle method for a technique that is used in many fields.
To learn for yourself, try to understand your state variables and your system. Take the acceleration you are seeing and divide the sphere's velocity (or velocity difference) by that acceleration. This will give you an idea of the time scale that the sphere needs to slow down on impact. Multiply by the velocity and you get a displacement, you can get an idea of how far that sphere will travel before slowing down.
Also, take a look at your time step. If the velocity multiplied by the time step allows the sphere to travel further than your threshold for detecting contact, then the sphere's will pass through each other. The same is true if your contact force doesn't increase as the sphere's begin to intersect.
If you want to take a deeper look at collision mechanics, look for topics under "dynamic behavior of materials". There you will see concepts for wave mechanics and elastic behavior. Most numerical methods transition to energy potential models rather than mass-spring-damper models, you can check out methods such as molecular dynamics, smoothed particle hydrodynamics, and peri-dynamics.
The main point is that these numerical methods operate on governing equations that don't allow particles (or your spheres) to pass through each other. The spring models, or potentials often have very (very) stiff responses when objects begin to intersect, as compared to the normal contact between objects.
A couple of points to take away:
Your integrator (i.e. time step) is likely too coarse or your collision detection is too fine, allowing the spheres to intersect.
Look up the discrete particle method (sometimes called the discrete element method), it is very popular and has many, many people using, studying, and publishing. You will find code, mass-spring-damper models, parameters, and other methods to help you reach your goal.

Linear Interpolation and Object Collision

I have a physics engine that uses AABB testing to detect object collisions and an animation system that does not use linear interpolation. Because of this, my collisions act erratically at times, especially at high speeds. Here is a glaringly obvious problem in my system...
For the sake of demonstration, assume a frame in our animation system lasts 1 second and we are given the following scenario at frame 0.
At frame 1, the collision of the objects will not bet detected, because c1 will have traveled past c2 on the next draw.
Although I'm not using it, I have a bit of a grasp on how linear interpolation works because I have used linear extrapolation in this project in a different context. I'm wondering if linear interpolation will solve the problems I'm experiencing, or if I will need other methods as well.
There is a part of me that is confused about how linear interpolation is used in the context of animation. The idea is that we can achieve smooth animation at low frame rates. In the above scenario, we cannot simply just set c1 to be centered at x=3 in frame 1. In reality, they would have collided somewhere between frame 0 and frame 1. Does linear interpolation automatically take care of this and allow for precise AABB testing? If not, what will it solve and what other methods should I look into to achieve smooth and precise collision detection and animation?
The phenomenon you are experiencing is called tunnelling, and is a problem inherent to discrete collision detection architectures. You are correct in feeling that linear interpolation may have something to do with the solution as it can allow you to, within a margin of error (usually), predict the path of an object between frames, but this is just one piece of a much larger solution. The terminology I've seen associated with these types of solutions is "Continuous Collision Detection". The topic is large and gets quite complex, and there are books that discuss it, such as Real Time Collision Detection and other online resources.
So to answer your question: no, linear interpolation on its own won't solve your problems*. Unless you're only dealing with circles or spheres.
What to Start Thinking About
The way the solutions look and behave are dependant on your design decisions and are generally large. So just to point in the direction of the solution, the fundamental idea of continuous collision detection is to figure out: How far between the early frame and the later frame does the collision happen, and in what position and rotation are the two objects at this point. Then you must calculate the configuration the objects will be in at the later frame time in response to this. Things get very interesting addressing these problems for anything other than circles in two dimensions.
I haven't implemented this but I've seen described a solution where you march the two candidates forward between the frames, advancing their position with linear interpolation and their orientation with spherical linear interpolation and checking with discrete algorithms whether they're intersecting (Gilbert-Johnson-Keerthi Algorithm). From here you continue to apply discrete algorithms to get the smallest penetration depth (Expanding Polytope Algorithm) and pass that and the remaining time between the frames, along to a solver to get how the objects look at your later frame time. This doesn't give an analytic answer but I don't have knowledge of an analytic answer for generalized 2 or 3D cases.
If you don't want to go down this path, your best weapon in the fight against complexity is assumptions: If you can assume your high velocity objects can be represented as a point things get easier, if you can assume the orientation of the objects doesn't matter (circles, spheres) things get easier, and it keeps going and going. The topic is beyond interesting and I'm still on the path of learning it, but it has provided some of the most satisfying moments in my programming period. I hope these ideas get you on that path as well.
Edit: Since you specified you're working on a billiard game.
First we'll check whether discrete or continuous is needed
Is any amount of tunnelling acceptable in this game? Not in billiards
no.
What is the speed at which we will see tunnelling? Using a 0.0285m
radius for the ball (standard American) and a 0.01s physics step, we
get 2.85m/s as the minimum speed that collisions start giving bad
response. I'm not familiar with the speed of billiard balls but that
number feels too low.
So just checking on every frame if two of the balls are intersecting is not enough, but we don't need to go completely continuous. If we use interpolation to subdivide each frame we can increase the velocity needed to create incorrect behaviour: With 2 subdivisions we get 5.7m/s, which is still low; 3 subdivisions gives us 8.55m/s, which seems reasonable; and 4 gives us 11.4m/s which feels higher than I imagine billiard balls are moving. So how do we accomplish this?
Discrete Collisions with Frame Subdivisions using Linear Interpolation
Using subdivisions is expensive so it's worth putting time into candidate detection to use it only where needed. This is another problem with a bunch of fun solutions, and unfortunately out of scope of the question.
So you have two candidate circles which will very probably collide between the current frame and the next frame. So in pseudo code the algorithm looks like:
dt = 0.01
subdivisions = 4
circle1.next_position = circle1.position + (circle1.velocity * dt)
circle2.next_position = circle2.position + (circle2.velocity * dt)
for i from 0 to subdivisions:
temp_c1.position = interpolate(circle1.position, circle1.next_position, (i + 1) / subdivisions)
temp_c2.position = interpolate(circle2.position, circle2.next_position, (i + 1) / subdivisions)
if intersecting(temp_c1, temp_c2):
intersection confirmed
no intersection
Where the interpolate signature is interpolate(start, end, alpha)
So here you have interpolation being used to "move" the circles along the path they would take between the current and the next frame. On a confirmed intersection you can get the penetration depth and pass the delta time (dt / subdivisions), the two circles, the penetration depth and the collision points along to a resolution step that determines how they should respond to the collision.

Physics [UE4]: Implement a "maximum compression" for vehicle-suspension

For a given vehicle, I implemented a suspension system on four wheels.
The system is based on Hooke's Law.
The Problem: The vehicle should not be able to touch the ground. When driving in a spherical container (inside), the suspension gets compressed up to 100%, making the vehicle chassis touch the underground, which leads to unwanted collisions that throw the vehicle around.
Despite that may being a realistical behaviour, our game aims for an arcade-feeling, so I am looking for a formula to implement a maximum compression, so that the vehicle chassis can't come closer to the underground than X percent of the suspension size at any given moment, without actually simulating a physical contact between the two rigid bodys. Thus, I need to apply a fake force to the suspensions.
My current approach:
If the vehicle chassis would in fact touch the suspension base (Sorry, I don't know the proper word to describe this. I mean, when the suspension is at maximum compression), a force equal in magnitude and opposite in direction relative to the force pushing onto the suspension would be applied to the vehicle chassis, forcing it to stop moving downwards.
Therefore, I receive my vehicles world velocity V.
To get the downwards-velocity, I get the DotProduct of the velocity and the BodyUpVector.
float DownForceMagnitude = DotProduct(VelocityAtSuspension, BodyUpVector);
FVector DownForce = DownForceMagnitude * BodyUpVector;
FVector CounterForce = -DownForce * WeightOnSuspension;
Okay, this pseudo-code works somewhat fine on even underground, when the vehicle lands on a plane after a jump. Driving on a increasing slope however (like driving on the inside-walls of a sphere), makes the suspension reach maximum compression anyway, so apparently my approach is not correct.
I am now wondering what the cause is. My weight calculation only is simulated by VehicleWeight / 4, since the Unreal Engine 4 has no functionality to receive weight at a given location. I am no physics-pro, so forgive me if this is easy to calculate. Could that be the issue?
I do not need a physically 100% plausible solution, I just need a solution that works, and sufficiently stops the downwards motion of my vehicle chassis.
Any help is appreciated.
Greetings,
I had this problem with a futuristic magnetic hovercraft.
I solved it by reducing the force by ln depending on suspensions extension levels like so:
y = ln(ln(x+e))
where:
x = Suspension extension lvl in % (-> 0 being fully compressed)
y = the factor that you multiply the force with
e = eulers number
Here a graphic to help what it will be like:
https://ggbm.at/gmGEsAzE
ln is a very slow growing function thats why it works so great for this.
You probably want to clamp the values (maybe between 0 and 100 idk exactly how your code behaves and how u want this "break" to behave)
Tailor the function to your needs, I just wanted to suggest u use the ln like I did to solve this Problem.
I added e to x first to make it go through 0,0 if u want to make it stop earlier just subtract from x before using ln.
Also notice depending on when/how you calculate / update your suspension this (and any function applied to the force based on the extension of suspension levels) may not work under some circumstances or at all.

Cocos2D Asteroids

For school I have to make a game for my iPod touch, I chose to do an asteroids game. I have just started with cocos2d but have read the wenderlich blog. I wanted to use chipmunk in my game, i want realisitc motion of the ship. Is there a tutorial on creating the asteroids motion?
Thanks.
Simple Way
Learn a bit about vectors. http://chortle.ccsu.edu/VectorLessons/vectorIndex.html
Movement is usually calculated by adding a vector scaled by a time delta to the current position. (Math talk makes simple things so complicated).
Basically: new_Pos = old_Pos + mov_Vec * time_delta
So by changing the mov_Vec you can increase/decrease speed.
You can also do it on x,y new_x = old_x + mov_x * time_delta
Using Physics Library
If you are using a physics library, you can apply force to an object to move it. You can also set the angular velocity if you want it to rotate.
If you were using Box2d you would do something like this:
body->ApplyImpulse( b2Vec2(1,1), body->GetWorldCenter() );
There's a difference between applying force and an impulse in box2d
Some sites to check out
http://gpwiki.org/
http://www.gamedev.net/
http://www.devmaster.net/
http://box2d.org/
Airship motion in space is pretty easy to simulate... I don't think you need a library for that.
The ship has a velocity vector: depending on your input method, you shall only add a vector to change the speed (or reduce modulo when braking, if braking is allowed).
Just limit the max modulo of the ship, and you're done.
Sorry if this isn't really a reply to your answer.
HIH

Particle stream should be the same length regardless of emitter speed

I'm writing a particle system for our student game, and I've run into a bit of a snag. I want to improve the effect on the ships' rockets, but I can't seem to figure out how.
Here's how the effect looks on a stationary ship:
And here's how it looks on a moving ship:
I want the flames to be the same length consistently. Here's Particle's Tick function:
void Particle::Tick(float a_DT)
{
// temporarily turned off to see the effect of the rest of the code more clearly
//m_Pos += m_Vel;
if (m_Owner) { m_Pos += m_Owner->GetParentSpeed(); }
m_Life -= 1;
if (m_Life <= 0) { m_Alive = false; }
}
Thanks in advance.
EDIT: To clear things up a bit, I want the effect to trail, but I want it to trail the same way regardless of the emitter's speed.
You're making the particles move faster or slower according to the parent ship's speed, but their lifetime is some constant that you decrement by one until you reach zero, correct?
What you probably want to do is set the lifetime to a distance value, rather than some number of ticks. Then, subtract the ship's speed (or whatever you're adding to each particle on each tick) from the lifetime. When lifetime goes negative, kill the particle.
I think that's what you want... but it might be cooler (and more realistic) if you make two changes to your algorithm:
The current behavior (length of the tail) is correct if the particle
speed coming out of your engines is based upon thrust (acceleration
rather than just speed).
Once a particle leaves the engine, any changes in speed/direction of
the ship have no effect on it. Once the particle is emitted, it's speed
and direction are constant until it fizzles out. This should actually
look pretty cool when you're turning the ship, or dramatically changing
acceleration.
Cheers.
If you want it to have its own length consistently then you'll need to normalize the parent's velocity by dividing it by the parent's speed. Obviously this will not work if the parent is sitting still so you'll need some sort of "idle" state for the particles in that case (random conical distribution or whatnot).
Also, only acquire the velocity in the constructor, and keep using it during the ticks.
Are there any random variables in the system? Number of particles per emitter, particle life etc? This would cause the trails to be of varying length.