Making a unicycle with Box2D - iphone

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.

Related

Unity bouncing ball miraculously gains height

I have a sphere with bounciness set to 1
The ball has no drag and uses gravity
It hits a platform, which has bounciness set to 1 and no friction
Yet, the ball bounces higher on every bounce, going to infinity. How is such a thing possible, when I have not given it any extra momentum?
The issue comes from the fact that physics in games happens in discrete frames, and that a moving object will be "inside" another at the frame where there is a collision. The physics engine then has to separate the objects before the next frame, and figure out how much energy to "bounce" with.
One of the steps to do this involves figuring out how much the objects overlap, and that's where this phantom extra energy is comin from. Less error in the overlap equals less error in the energy.
Don't fiddle with the bounciness; those are naive solutions, not to mention they sidestep the issue rather than solving it.
What you should do is to fix what's wrong with your collisions. That can be done a number of ways, the most appropriate/performant of which depends on each specific game:
Increase your physics frame rate (decrease fixed delta time). This reduces overlaps and makes physics frames "smoother". It doesn't really solve phantom energy though; only makes it's causes and effects smaller (maybe so small they become unnoticeable, which is all you need).
Set your sphere's collision detection method to Continuous Dynamic,
and set your ground to static. If you need the sphere to collide with
other stuff, those other stuff present similar issues, and those need
to be non-static, set their rigidbodies' collision detection method
to Continuous. (This is the method I most often find to be the best, but I've had projects where others were better for various reasons)
Increase your Default Solver Velocity Iterations
Change your solver type to Temporal Gauss Seidel
I have had a similar issue with javascript/html/css canvas animations. I have no explanation for this. Use a number like 0.99999 or 0.969399 and that should do the trick. I do get what you mean though it's weird. Just get close to 1. That's all I can say. I hope this helps anyway.

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.

iPhone add inertia/momentum physics to animate "wheel of fortune" like rotating control

I'm trying to create a new kind of rotary control with a look and feel of a real massive wheel supported on a pin, able to rotate around it's center point with a certain degree of damping, which will eventually bring the wheel to a halt. Think "wheel of fortune".
Rotary control sample project
When working with native UITableView and/or UIScrollView, they can be "flicked" in one direction and continue scrolling in that direction for a while. I know similar effect may be achieved with the animation curve.
What I'm interested in is how to calculate how far the interface element should scroll/rotate based on the distance/speed that the finger travelled. Different types of "flicks" would produce different behavior by transferring "momentum" to the wheel. Can anyone suggest examples of such calculations?
I'm particularly interested in applying the same concept of inertia to a custom rotary control as described here: Rotary control on stack overflow . The current examples, and even the convertbot app mentioned in the examples do not use inertia. The wheel simply follows the finger and snaps to pre-defined positions. I want to make a similar wheel feel like it has real mass to it, so it can be flicked and will spin in a predictable manner until coming to a smooth halt. (Think "wheel of fortune" type shows).
How can I achieve this kind of "wheel of fortune" inertia-based behavior for a rotary control that would make the control feel like it has real mass to it?
Thank you!
Implementing a fully realistic mass effect is not that trivial, and maybe requires too much work (especially for such a simple task), thus I'd ignore physic's laws (except those strictly needed) and make everything simpler.
A momentum is r x F where r is the radius and F is the force applied. Since it depends on the radius, the more you get far from the center of your wheel the greater will be the momentum. Let's ignore it and suppose that the force is tangent and is applied always at r=wheelWidth/2.
Besides, instead of computing force you may simply make it depends on the speed of the gesture (easier than computing force, since it requires mass and acceleration). Thus we can image that a faster touch will correspond to a greater momentum.
Of course, the gesture will never be perfectly horizontal or vertical, thus you can assume that every time there are two torques applied: the first corresponding to the vertical movement and the second to the horizontal.
You can get the gesture speed you may simply compute initial and final position of the touch, and divide their difference by the time elapsed.
To get the effect of slowing down you must assume that, when the wheel is moving, there is always an opposite torque. You can define it at compile time or make it dependent from the width of your wheel (such that larger wheels will slow down faster).
Now you have pretty much all that you need...good luck :)
I found that using iCarousel, it is possible to create a wheel like control with inertia/momentum!

How would you keep a top view of a train on the tracks with the Box2D physics engine?

I think it would be fun to model a top view of a train following a track, traversing switches and so on, using a physics library like Box2D. What joints and motors would I need to make this work?
I'm curious about how to implement the forces needed to make the car follow a spline track so it can bump into other train cars, pedestrians, DeLoreans etc. Just saying "the car is now at spline(t)" for each time step would create excessive forces in the physics engine. If I understand correctly, you have to stick the car onto the track with one force, constrain its angle to tend towards parallel with the track with another (or stick the front and back of the car to the track with two forces), and create another force to propel the train forward. I'm looking for some details on how to accomplish these things.
I believe it would be easier without "real" physics, like the ball movement of games such as Luxor or Tumble Bugs. Meaning: let the train follow a spline which is defined by the tracks.
Using phyiscs is probably overkill to make a train follow a track and could lead to all kinds of undesired side-effects, including jerky motion, train derailing, train getting stuck on junctions, etc.
You could still join the individual wagons together using physic joints, however. Just make sure that only the locomotive gets acceleration forces, the rest of the train just follows or is pushed but stays on the spline.
Why are you worried about keeping it "on the tracks"? Where is it going to go? Gravity should keep it down, object intersection should keep it up, and so the only directions you need to worry about are forward and backwards. That's where a motor comes in, and you're done. The rest is decorations.
In response to edit of problem:
Siderails. And have the train long enough / rigid enough compared to its width that you can navigate crossings (make them closer to right angles to minimize the crossing problems.
A top-down view (i.e. seeing the train from the sky) doesn't really require a 2d physics engine - if I understand you correctly. In fact, it seems like it wouldn't really help with the problem (if you want a train simulation), but then maybe you just wanna try it out for fun. :)
However, what about putting something like a slider joint on the train and the cars, and a motor on the locomotive. The slider joint might need some special implementation; you probably want to run the train along a spline and not a segment of straight lines, right?
Some sort of ball joint would connect the cars together.
The implementation is not so toughand I was able to prototype something in a few hours that does the basic job. It will require a lot of work to make it run smoothly, but it's essentially just "siderails."
Being top-down you obviously first must turn off gravity in Box2D. Second, build a train. Treat train wheels like car wheels and it'll suddenly get a lot more simple. For tracks you have a few choices:
Create your own game object (not in the box2D world) that is a simple line the train will then "follow" (you can use motors on train wheels to "steer" towards the line). Then just overlay the line with some nice wide "rail" graphics and you have a nicely faked system. Tell the wheels to turn off if it strays too far from the line and presto, you have a derailment.
Create actual physical rails - outside rails (like siderails) that the trains "wheels" will bump into. They will have to have gentle curves in this instance, which could be very difficult given the limited resources you have (simulating a nice slow curve out of boxes in Box2D is rough on the processor)
Then just let your train go!