iPhone cocos2d box2d body collision detection without applying force - iphone

I am writing Cocos2D box2d game for iPhone.
I've 2 dynamic bodies, and I hope they are applied force from outside, but they don't apply force each other and detect their collision.
How can I achieve this?
And also I hope they move together at the same position after collision.
How can I do this?

they don't apply force each other and detect their collision
Sounds like you might want to look at collision filtering. This answer has a bit of code that changes the collision filtering index of a body dynamically https://stackoverflow.com/a/11283206/735204
they move together at the same position after collision
Probably some kind of joint (eg weldjoint?)
From the manual: http://www.box2d.org/manual.html
Joints are used to constrain bodies to the world or to each other. Typical examples in games include ragdolls, teeters, and pulleys. Joints can be combined in many different ways to create interesting motions.
Some joints provide limits so you can control the range of motion. Some joint provide motors which can be used to drive the joint at a prescribed speed until a prescribed force/torque is exceeded.
Joint motors can be used in many ways. You can use motors to control position by specifying a joint velocity that is proportional to the difference between the actual and desired position. You can also use motors to simulate joint friction: set the joint velocity to zero and provide a small, but significant maximum motor force/torque. Then the motor will attempt to keep the joint from moving until the load becomes too strong.

Sorry about last answer, just checking that I can write it.
What about this?
bodyDef.isSensor = true;
and use ContactListener to detect collision. Box2d for collision detection
Also you can use box2d filters. For example:
REMEMBER: if groupIndex < 0, same bodies never collide with each other. That is what you need.
b2Filter bodyFilter;
bodyFilter.groupIndex = -1;
bodyFilter.categoryBits = 0x0002;
fixtureDef.filter = bodyFilter;

Related

Pymunk PinJoint with locked rotation with respect to bodies

I'm trying to create a simple chemistry simulator with atoms (circles) and bonds between them. The problem I'm having is that when atoms 'bond' using a pin joint, the circles rotate independently of the joint. I've tried using more than one pin joint, but the molecules end up oscillating, sometimes wildly, as they stretch and correct themselves. I would appreciate any ideas.
Have you tried to use a RotaryLimitJoint in addition to the PinJoint? It limits the relative rotation between the bodies: http://www.pymunk.org/en/latest/pymunk.constraints.html#pymunk.constraints.RotaryLimitJoint
My workaround is to create two pinjoints. One from the centres of each of the bodies, and one, very short (0.1), at the contact point of the two bodies. This results in the two bodies (atoms) being very close to each other, but they rotate as a single object. I can set collide_bodies = False for both joints, which reduces processing. There is a little movement when the constrained bodies collide with a third body, but overall the solution works well.

How do I make a SKSpriteNode avoid another SKSpriteNode?

I am working on an AI mode for a SpriteKit game I am making in Xcode. I have dynamic physics bodies which can be launched towards the AI. I want to make it so that when one of these bodies is within a certain radius of the AI, the AI tries to dodge it. I have started working through different routes and got decent results.
1st method (pseudocode): Check AI.position.x and AI.position.y and compare to incomingSprite.position.x and incomingSprite.position.y. Break this comparison into quadrants if both x and y are within radius. (i.e. incomingSprite is bottom left relative to AI, bottom right, etc). Based on this info move the AI's position to move away from it.
cons:
-lots of code and calculations in update function to account for multiple incoming sprites
-depending on dx and dy of incoming sprite, the AI often make illogical decision
2nd method (pseudocode): Calculate distance from AI to incomingSprite. Then check dx and dy of incomingSprite and set dx and dy to go in reverse direction of incomingSprite. This seems logical. I am a little rusty on reversing vectors to do this. I feel like this might be possibly a good idea though.
Is there a better method to accomplish this? Perhaps a force field on the magnet I could use to repel the AI at a certain strength so that if the incomingSprite is fast enough it will override and still collide anyway? Im concerned about memory as most of the AI logic is in the update function, which can cause big problems if I'm not careful.
Edit: I decided to use the electric field and gave the incoming sprites a positive charge so that they are repelled by the AI. This makes things accurate/lightweight and more interesting. If the incoming sprites are fast enough, they will break through the electric field and still collide with AI. This also gives room as an additional difficulty parameter in my game (the stronger the field, the harder it is to get the incoming sprites to collide with the AI).

How to make Hinge Joint more rigid

I'm trying to create a chain in unity3d. A player should be capable of grabing one side of it and pull it to different location. So i created some grids and connect them together. It all works fine, the problem is only when user pulls a bit faster, then I got some spaces bettwen seperate grids. Is there anyway to set max distance on that?
Btw. I'm doing these in 2d so i have 2d Rigidbody and 2d Hinge joint.
Thanks!
The solverIterationCount of rigidbodies affects the smoothness of physics when they are moving fast. You should try increasing it or dynamically adjusting it according to the speed of the rigidbodies to increase stabilty
http://docs.unity3d.com/Documentation/ScriptReference/Physics-solverIterationCount.html
There a number of ways to tackle this issue, all with the up sides and down sides:
increasing accuracy:: this is usually the first place new game designers go, and crank up accuracy to the max. But then end up playing the price later when performance plummets. So be gentle, try to find a good balance, and if it does not cut it make up the rest with other tricks.
The main ways to increase accuracy are, increasing fixed times interval, and increasing ridged body Iteration count
.
Increasing restrictions::This often requires the most time, but cutting corners allows for smoother more predictable physics and can increase performance
small example:: the top link of the chain only needs to simulate rotation on the ridged body
.
Cheating:: find any way to make things easier, fake it
for example:: does the image really need to match the physics? Why not make sure the sprites stick together, but alow the physics to have small gaps
playing with the same concept more or less this week, experimented some with 2D Unity joints, I think the issue you are having is identical to one I had yesterday, the force you are applying 'breaks' joints for some frames, hence that almost 'spring' joint effect, make sure the mass and/or force applied are not too heavy, also maybe increase the chain parts mass, makes the joints more solid too.
In Editor, Hinge Joint -> Use Spring = true; Spring/Damper/Target Position = 0.

Making a unicycle with Box2D

I'm fairly new to Box2D and trying to figure out the best way to make a unicycle. The unicycle essentially is in two pieces, the wheel and the stem (with seat post etc). I've tried attaching the two with a revolute joint and using a motor for the wheel, which works well except that the stem is then subject to forces from the movement of the wheel. I want to be able to directly control the rotation of the stem (via the accelerometer on the iPhone), and have it unaffected by the movement of the wheel, except to maintain its position based on the position of the wheel.
What is the best way to do this? How do you control rotation of b2Body's? Should I be using a distance joint instead? Any help would be appreciated.
I see several routes, depending on your needs. Which way is preferable is up to you and your game.
1. Fix the stem's rotation
For the bodyDef for the stem set the fixedRotation-flag to true. This prevents any rotation of the stem (be it by forces from the motor joint, (de)acceleration or collisions.
Than you'd have to manually set the rotation each tick. This is easy if it's purely based on the iPhone's position. If you still want to calculate other factors into it, things might get from a bit more complicated (e.g. adding rotation if stem leans too far in one direction) to somewhat painful (have collisions affect the rotation).
2. Constantly apply balancing forces to the stem
Each tick read the stems angular velocity and apply countering forces to balance the stem.
While this would probably be more complicated to implement correctly (always find the right force to apply etc.) it may result in a more realistic behaviour as the fixed rotation obviously removes most reactions stem movement would have and how the stem itself is affected by the world.
3. Don't actually use a wheel
While your layout is the obvious choice for a unicycle (and seems to be a somewhat popular choice for all kind of characters) it might not be the best choice from a gameplay point of view.
Instead you could combine the stem and wheel fixtures in a single body (or attach them with a prismatic joint) and create all movement by applying forces to this body. A sensor at the bottom can inform you of ground contact to determine if movement forces are to be applied.
This way you'd get rid of all the forces a wheel creates (forces to the stem may not be the only unwelcome ones in gameplay) and still have it react to all external forces.

Objects that defy gravity but collide with others in Box2D. How?

newbie to iPhone game development and Box2D here.
I'm developing a game in which I can move (drag) otherwise stationary objects that can collide with other objects.
How do I make these objects stationary in a Box2D world with gravity while maintaining their ability to collide with dynamic bodies?
One random thought is to exert a force equal to gravity on these objects all the time. Any better or simpler approaches? Will static bodies help?
Static bodies will collide with dynamic objects but not other static objects. That sounds like what you want, but it's not clear from your description what the "other bodies" in question are.
You cannot disable gravity on a per-object basis; exerting a force equal to the opposite of gravity will usually work but can, due to rounding errors, accumulate small velocities. A better approach is to set gravity to 0 and manually apply a gravitational force on the objects you do want affected by gravity.