Pymunk PinJoint with locked rotation with respect to bodies - pymunk

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.

Related

SpriteKit SKPhysicsJointFixed odd behaviour

I am trying to connect together two SKNodes which both have equal size circular physics bodies. They are positioned so as to be touching each other, and I want them to be locked together. From the documentation, it sounds like I want a SKPhysicsJointFixed, and I have tried creating one with the anchor point being the midpoint between the two nodes - like this:
let fixedJoint = SKPhysicsJointFixed.joint(withBodyA: atom1.physicsBody!, bodyB: atom2.physicsBody!, anchor:midPoint)
but this causes an odd behaviour where after the joint is made the top node falls through the bottom node - where before the joint existed the physicsbodies rested against each other.
If I use a pin joint instead with the same code - it works as expected ie:
let pinJoint = SKPhysicsJointPin.joint(withBodyA: atom1.physicsBody!, bodyB: atom2.physicsBody!, anchor:midPoint)
locks the bodies together as I want them to be. I guess this is a perfectly fine solution - but I'm confused something about what is going on. Why does my pin joint do what I thought the fixed joint would do, and why does the fixed joint not do what I thought it would?
Perhaps you were running into the same problem I ran into. I've found that SKPhysicsJointFixed behaves very strangely if the SKNode.zRotation property in the two nodes you're joining is different. Here's the behavior I was trying to get, having nodes of certain types stick together when they collide. Note how, after the collision, they rotate around their common center of mass.
But I was often getting this sort of thing, and often even stranger than this. Notice that not only does it not rotate as expected, it starts to wiggle as it approaches the wall.
As you can see, the difference between the two scenarios is that the zRotations are equal in the first case, unequal in the second case. Seems like a bug in SpriteKit, if you ask me.
One workaround is simply to explicitly set the two zRotations equal before you create the joint, but this was unacceptable for my purposes. Fortunately, as you already found, you can consistently get the expected behavior from SKPhysicsJointPin. Of course, if you want the pin joint to behave like a fixed joint, you'll have to set the joint's shouldEnableLimits property to true.

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.

iPhone cocos2d box2d body collision detection without applying force

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;

Open GL - ES 2.0 : Touch detection

Hi Guys I am doing some work on iOS and the work requires use of OpenGL es. So now I have a bunch of squares, cubes and triangles on the screen. Some of these geometries might overlap. Any ideas/ approaches for touch detection?
Regards
To follow up on the answer already given, squares, cubes and triangles are convex shapes so you can perform ray-object intersection quite easily, even directly from the geometry rather than from the mathematical description of the perfect object.
You're going to need to be able to calculate the distance of a point from the plane and the intersection of a ray with the plane. As a simple test you can implement yourself very quickly, for each polygon on the convex shape work out the intersection between the ray and the plane. Then check whether that point is behind all the planes defined by polygons that share an edge with the one you just tested. If so then the hit is on the surface of the object — though you should be careful about coplanar adjoining polygons and rounding errors.
Once you've found a collision you can easily get the length of the ray to the point of collision. The object with the shortest distance is the one that's in front.
If that's fast enough then great, otherwise you'll probably want to look into partitioning the world or breaking objects down to their silhouettes. Convex objects are really simple — consider all the edges that run between one polygon and the next. If only exactly one of those polygons is front facing then the edge is part of the silhouette. All the silhouettes edges together can be projected to a convex 2d shape on the view plane. You can then test touches by performing a 2d point-in-polygon from that.
A further common alternative that eliminates most of the maths is picking. You'd render the scene to an invisible buffer with each object appearing as a solid blob in a suitably unique colour. To test for touch, you'd just do a glReadPixels and inspect the colour.
For the purposes of glu on the iPhone, you can grab SGI's implementation (as used by MESA). I've used its tessellator in a shipping, production project before.
I had that problem in the past. What I have used is an implementation of glu unproject that you can find on google (it uses the inverse of the model view projection matrix and the viewport size). This allows you to map the 2D screen coordinates to a 3D vector into the world. Then, you can use this vector to intersect with your objects and see which one intersects (or comes really close to doing so).
I do hope there are better ways of doing this, so I look forward to other answers as well!
Once you get the inverse-modelview and cast your ray (vector), you still need to know if the ray intersects your geometry. One approach would be to grab the depth (z in view coordinate system) of the object's center and extend (stretch) your vector just that far. Then see if the vector's "head" ends within the volume of your object or not (you need the objects center and e.g. Its radius, if it's a sphere)