Cocos2d Chipmunk gravity property - iphone

I need to imitate radial (planetary-) gravity when all dynamic bodies in the space are attracted to the static body situated in the center of the screen. I set
space->gravity = ccp(0, 0);
I create dynamic bodies with calling their creating methods in -init, which will fall on this central body from other sides like here http://www.youtube.com/watch?v=2BxkbXfEWg4&feature=player_embedded from 0:12.
Questions:
how can I set gravity vector individually for every single object? I plan to real-time reassign gravity vector, based on objects coordinates changes.
what actually have property of gravity: sprite, body or shape?
is it a more simple way to realize this effect?

Scott Lembcke gives the answer on Cocos2d forum here:
http://www.cocos2d-iphone.org/forum/topic/35621?replies=4#post-171187

Related

How to make a sprite have gravity?

xcode 5 iOS7 sprite kit.
My wish is to make a sprite that has its own gravity.
Like a planet. If another sprite comes within a certain range of it, it will slowly pull the other sprite closer.
I have two sprites. One moving and one stationary. When the moving sprite gets in a given distance of the stationary sprite the stationary sprite gravity should slowly pull the other sprite towards it. This way the moving sprite would change its path in a soft curve.
My idea would be to calculate the distance from the stationary object to any other object and if close enough start pulling and if the moving object gets out of range ageing, then stop pulling.
Would probably need to research some vector calculation.
Thats my immediate thoughts.
Is this possible and how? Does it already exist?
A friend of mine did this for his physics dissertation. multibody gravity simulation. So yeah you can but you need to be willing to learn some maths. Apparently there is a clever optimisation to make it run decently nlog(n) rather than n^2). you probably want to ask this on the physics version of stack overflow to get a good answer. I have the code at home ... will post it later but you will want an explanation - i used it in an xna app. Its badass once you get it working - although if you want naturally orbiting objects then you will want to code them using parametric equations for easy and cool orbits. Simply because its hard to solve and with time even using double will result in some errors (the good implementations also work out the error and adjust - again will post later). But the real problem is solving for stable orbits. You then use the algorithm for free moving bodies such and player objects / npcs. Although solving accurate movement for npc in a changing field is v hard.
you want to look at this question: Jon Purdys answer is the one you want
multi body physics - gravity
and this one (which is linked from above) ...
https://gamedev.stackexchange.com/a/19404
There is not a dead-simple way of doing that in any platform as far as I know maybe except for some game engines/platforms that export for different platforms (cocos2d, construct 2 etc).
What you need is a physics engine whether you write one (which is a complicated but fun thing to do) or use an available one.
Luckily I've found a link describing the usage of the famous 2D physics engine "Box2D" on iOS.
This one explains how you can include Box2D in an openGL application (but you can apply this to other environments (sprite kit) I think altough I'm not an iOS guy);
http://www.iforce2d.net/b2dtut/setup-ios
Anyways, you now know what to look for...
For iOS 8.0+ : you have SKFieldNode : radialGravityField()
For iOS 8.0- : one solution could be : 3 to 9
add your sprite ( planet ) with its physics
add an invisible SKNode ( the gravity zone ) with its own physics, as a child of your sprite, but with a radius much more than your sprite's one
you have a little explanation about invisible node here : https://developer.apple.com/documentation/spritekit/skphysicsworld
both, your sprite and the invisible node are centered in a zero gravity world
we look for contact and not collision ( set correctly your bit masks )
when any object get in contact with the invisible node ( gravity zone ), first you remove any moving action or impulse from it and then we add to this object an SKAction to move it toward the center of your sprite ( planet )
at second contact between this object and your sprite ( planet ), you remove all actions again from the object with a velocity = zero

Sprite Kit Physics Body Complex Shape - Spritekit

I have this situation: http://mokainteractive.com/example.png
I'd like to move the white ball inside the red track and detect wherever the balls touch the limit of the red track.
Which is the best solution? I have to create multiple transparent shape along the borders? Do you have other ideas?
thanks so much
In iOS8 you can create a single physics body for that kind of shape.
Make a texture of your shape with p.e. Adobe Illustrator and use this method:
init(texture texture: SKTexture!,alphaThreshold alphaThreshold: CFloat,size size: CGSize) -> SKPhysicsBody
The SKTexture is your shaped image. The body is defined by the colored pixels.
The alphaThresHold: The minimum alpha value for texels that should be part of the new physics body.
The Size is clear I think.
The texture is analyzed and all invisible pixels around the egg are ignored and only the color pixels are interpreted as the body of the SKPhysicsNode. You should use too many of these because they are very expensive to calculate for the Physics Engine.
Variations of this method are found in the SpriteKit Class Reference.
To your problem. Make an inverse texture of your area which should be transparent and pass it as texture to the physics body. It will be analyzed and a body around the free zone is created.
You cannot create a single physics body for that kind of shape.
Using bodyWithPolygonFromPath: will only allow you to create a convex polygonal path which obviously does not work for your shape.
I think you have 3 options here:
Use a number of bodyWithPolygonFromPath: bodies (probably the hardest to do and time consuming).
Use a number of various size bodyWithRectangleOfSize: bodies (not so hard but time consuming).
Use only straight lines in your image and use bodyWithRectangleOfSize: (the easiest and fastest). If you choose this option remember you are still free to rotate your straight lines to various angles.

Rope breaks using Revolute joints

i am working on rope physics. i have implemented one rope using Revolute joints ..
I'm making rope connecting dynamic bodies (via b2RevoluteJoints).i successfully created it.Now i also attach one dynamic body at the end of rope . & i m releasing my this rope with this body downwards , now somehow my joints between my dynamic rope bodies are stretched & then breaks , I want my rope looks smoother.
my joints are like this
b2RevoluteJointDef revoluteJointDef;
revoluteJointDef.bodyA = referenceBody;//provided by testbed
revoluteJointDef.bodyB = lastLink;
revoluteJointDef.localAnchorA = startPos;//world coords, because m_groundBody is at (0,0)
revoluteJointDef.localAnchorB.Set(0,0);//center of circle
world->CreateJoint( &revoluteJointDef );
revoluteJointDef.bodyA = lastLink;//the last added link of the chain
revoluteJointDef.bodyB = chainBase;
revoluteJointDef.localAnchorA.Set(0,linkWidth);//the regular position for chain link joints
revoluteJointDef.localAnchorB.Set(0,linkWidth);//a little in from the edge of the circle
world->CreateJoint( &revoluteJointDef );
Is there any way to make strong joints ??
can we achieve this by working on Density of bodies & gravity of world ??
please help .....
I had a similar problem (but with the centrifugal force of swinging a larger object at the end of the rope). To solve the problem of the breaking chain/rope you need to make the larger object less dense, but this then introduces a knock on problem - now your "larger" dynamic object gets held correctly by the rope but does not interact with the rest of the world as it should.
To solve this problem I did something a bit hacky and implemented my own collision handler which would apply a collision impulse to the thing that my larger object collided with as if it were heavier. So...
make your object at the end of the rope very low density so that the rope holds
implement some supplemental collision handlers for your object to make it seem like your object is more dense to other objects (sensor = true may help with this as well).
It is not strictly in the spirit of the physics simulator, as we should be able to set our parameters and let the rules take care of everything - basically it would be nice if the revolute joints were unbreakable.

Physics vs graphics fighting each other (box2d)

so I have a ball (sprite subclass) that can be dragged around the screen and updates it body to tell the world its position.
The problem is, when I apply a force to the ball while the ball is being touched (thus being controlled by a finger), I have two pieces of code fighting against each other to update the sprite's visual position.
The world stepper is trying to follow through the physics and update the ball's position. The touch methods however are also trying to update the ball's body and graphic position. Ideally, when touched I would like to kill off any physics affecting the ball.
So what exactly should I be trying to do to consolidate this? This is also creating issues for collisions and filtering. Any help appreciated. Thanks
Do you want the ball to have an accurate physics simulation? If not, you could always use the SetTransform method of the b2body class like this.
CGPoint ballLocation = ;//use the touched location for this
b2Vec2 vecBallLocation = b2Vec2(ballLocation.x / 32, ballLocation.y / 32);//calculate this on your own
b2Body * ballBody = ;//replace this variable with your ball's b2Body;
ballBody->SetTransform(vecBallLocation, ballBody->GetAngle());
Do not set the ball sprite's position manually. Leave this up to the physics simulation. Your code will get really messy over time if you have to keep track of what sprites you set the position of manually and which ones use the physics simulation to update their positions. This way is also much easier.
When the physics object is being dragged, set its velocity and angular velocity to 0,0 before running the physics step simulation. You may also want to temporarily get the physics object's position, then step, then set the body's position back, then apply whatever touch dragging offset you got from moving the finger to the body.

Static and moving shapes in spacemanager

Dear all,
I have an application that uses cocos2d spacemanager with gravity set to a specific value.
If i want to make a shape in the middle of the screen it will fall down to the floor, if i set the gravity to zero all other object will not move as supposed, if i use a second spacemanager and set its gravity to 0 i cant detect collision between objects from different spacemanagers. how can i add a shape that wont fall down in the middle of the screen and detect its collision while other objects behave correctly according to the gravity set.
Also a question is, should i use shapes (Circle, rectangle, ... etc) with spacemanager and if i want to use a ccsprite (image) i should put it in a shape or i can use the sprite alone (e.g. a tree is not a rectangle or circle collision and reflection wont be natural how can i do this).
regards
Every shape has a property called mass. If you want a shape to be static and respond to collisions just set mass to STATIC_MASS like this:
cpShape *ball = [smgr addCircleAt:cpv(440,70) mass:STATIC_MASS radius:10];
to ad an image, do that:
cpShape *ball = [smgr addCircleAt:cpv(440, 70) mass:STATIC_MASS radius:10];
[super initWithShape:playerShape file:#"ball.png"];
If this doesn't work, set up a cpCCSprite in it with a shape.
You can search for cpCCSprite on google, im sure you'l find something :)