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

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!

Related

Create natural disaster model in unity3D

I am working on a application where, I would like to make a 3D terrain model of my country in unity3D in clusive of hills, mountains and rivers. So far I've been able to use mapbox to import the country map because unity wrld sdk doesn't yet support my country.
However the end goal is to create an application capable of representing natural disasters. Example, I have the country. I would like to know how would one go about causing rain to occurred that would essentially affect the "water levels" of the river and essentially show a flood. Basically, after I bring in the terrain how do I "act" on it to cause a landslide.
Any help or tutorial pointing to such would be welcomed.
You will need different models for each natural disaster. You will always only get a rough estimate of what may happen as your data will never represent the actual terrain. (For example earthquake, you may be able to reproduce damage to structures but never be able to predict if there will be a drift in the earth itself)
Rain/ Flood
A really simple simulation of rising ground water is slowly moving a "water" plane up. This crude approach will demonstrate which areas are going to be under water quite easily. For a detailed flood simulation you will need a fluid simulation of any kind (there are quite a few on the asset store)
Avalanche
Treat it as a fluid system with a strong resistance.
Vulcan
Almost the same as a flood, just with more viscosity.
Earthquake
You may be able to simulate the damage of an earthquake if all your objects have some kind of break point and the earthquake is added force to an area. A set force has an certain chance to destroy the object in the area. (Think of it in terms like any castle destroy game aka Flappy Bird, the bullet is your local earthquake and the castle your terrain + building/ trees)
Fire
You will need something like a burn value. Higher value = the longer it burns, harder to put out, faster spread. If a fire starts at any given point, it grows around. A river would have a value of 0, same as mountains. A forest would have a high value, a grass plain a low value. If you want to simulate a hot dry summer, your terrain could add a fixed value to everything, grass gets drying and thus has a higher chance to spread fire.

How to train a neural network to generate movements based on a training set of hand motions?

I am making a game in Unity that involves creatures whose animations are determined by physics. For example, to move a limb of a creature, I can apply forces to the rigidbody it's associated with. I know how to apply forces programmatically through a script to create movements, but I'd like to create more complex and organic movements and thought that I might be able to use a neural network to do this.
I'd like each of the creatures to have a distinct way of moving in the world. I'd like to first puppeteer the creatures manually using my hand (with a Leap Motion controller), and have a neural network generate new movements based on the training I did with my hand.
More concretely, my manual puppeteering setup will apply forces to the rigidbodies of the creature as I move my hand. So if I lift my finger up, the system would apply a series of upward forces to the limb that is mapped to my finger. As I am puppeteering the creature, the NN receives Vector3 forces for each of the rigidbodies. In a way this is the same task as generating a new text based on a corpus of texts, but in this case my input is forces rather than strings.
Based on that training set, is it possible for the NN to generate movements for the characters (forces to be applied to the limbs) to mimic the movements I did with my hand?
I don't have that much experience with neural networks, but am eager to learn, specifically for this project. It would be great to know about similar projects that were done in Unity, or relevant libraries I could use that would simplify the implementation. Also, please let me know if there is anything I can clarify!
Not really an answer but would not fit for comments
I'm not sure the strategy you want to apply to train your model is the right one.
I would go for reinforcement learning methods (you can check this question for more infos about it) using, for example, the distance traveled by the center of mass of the creature on the x-axis as a fitness. If this leads to weird behaviours (like this well known robot) you could, for example, think of strategies like penalizing your individuals given the distance traveled on y and z axis (still by the CoM) to try having guys that keep there CoM on the same plane.
Without knowing exactly what you want to achieve this is hard to give you more advices. Although, if you are not looking only for neural network based techniques, there is this really great paper you might want to have a look at (here is the video of their results).

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.

Falling Sand simulation

I'm trying to re-create a 'falling sand' simulation, similar to those various web toys that are out there doing the same thing - and I'm failing pretty hard. I'm not really sure where to begin. I'm trying to use cellular automata to model the behavior of the sand particles, but I'm having trouble figuring out how to make the direction in which I update the 'world' not matter...
For example, one of the particle types I'd like to have is Plant. When Plant comes in contact with Water, Plant turns that Water particle into another Plant particle. The problem here though is that if I'm updating the game world from top to bottom and left to right, then a Plant particle placed in the middle of a sea of Water particles will immediately cause all of the Water particles to the right and below that new Plant particle to turn into Plants. This is not the behavior I am expecting. =(
One straightforward solution is to not do each iteration in-place. Instead, every time you update the world, create a copy of it... then look at the original, but update the copy. That way the order of updating does not matter any more, because you are completely disregarding your updates while you're looking for particles.
Don't program it in a sequential way (looping over all particles) but use real simulation programming techniques in which every particle is treated as an individual object/agent that obeys the laws of physics and that can act (run) asynchronously and respond to "events" (interactions with other particles).
If making every sand particle a separate object is too fine-grained, then divide the world into small blocks of let's say 1000 particles and simlute the behavior of these blocks instead.

Jelly physics 3d

I want to ask about jelly physics ( http://www.youtube.com/watch?v=I74rJFB_W1k ), where I can find some good place to start making things like that ? I want to make simulation of cars crash and I want use this jelly physics, but I can't find a lot about them. I don't want use existing physics engine, I want write my own :)
Something like what you see in the video you linked to could be accomplished with a mass-spring system. However, as you vary the number of masses and springs, keeping your spring constants the same, you will get wildly varying results. In short, mass-spring systems are not good approximations of a continuum of matter.
Typically, these sorts of animations are created using what is called the Finite Element Method (FEM). The FEM does converge to a continuum, which is nice. And although it does require a bit more know-how than a mass-spring system, it really isn't too bad. The basic idea, derived from the study of continuum mechanics, can be put this way:
Break the volume of your object up into many small pieces (elements), usually tetrahedra. Let's call the entire collection of these elements the mesh. You'll actually want to make two copies of this mesh. Label one the "rest" mesh, and the other the "world" mesh. I'll tell you why next.
For each tetrahedron in your world mesh, measure how deformed it is relative to its corresponding rest tetrahedron. The measure of how deformed it is is called "strain". This is typically accomplished by first measuring what is known as the deformation gradient (often denoted F). There are several good papers that describe how to do this. Once you have F, one very typical way to define the strain (e) is:
e = 1/2(F^T * F) - I. This is known as Green's strain. It is invariant to rotations, which makes it very convenient.
Using the properties of the material you are trying to simulate (gelatin, rubber, steel, etc.), and using the strain you measured in the step above, derive the "stress" of each tetrahdron.
For each tetrahedron, visit each node (vertex, corner, point (these all mean the same thing)) and average the area-weighted normal vectors (in the rest shape) of the three triangular faces that share that node. Multiply the tetrahedron's stress by that averaged vector, and there's the elastic force acting on that node due to the stress of that tetrahedron. Of course, each node could potentially belong to multiple tetrahedra, so you'll want to be able to sum up these forces.
Integrate! There are easy ways to do this, and hard ways. Either way, you'll want to loop over every node in your world mesh and divide its forces by its mass to determine its acceleration. The easy way to proceed from here is to:
Multiply its acceleration by some small time value dt. This gives you a change in velocity, dv.
Add dv to the node's current velocity to get a new total velocity.
Multiply that velocity by dt to get a change in position, dx.
Add dx to the node's current position to get a new position.
This approach is known as explicit forward Euler integration. You will have to use very small values of dt to get it to work without blowing up, but it is so easy to implement that it works well as a starting point.
Repeat steps 2 through 5 for as long as you want.
I've left out a lot of details and fancy extras, but hopefully you can infer a lot of what I've left out. Here is a link to some instructions I used the first time I did this. The webpage contains some useful pseudocode, as well as links to some relevant material.
http://sealab.cs.utah.edu/Courses/CS6967-F08/Project-2/
The following link is also very useful:
http://sealab.cs.utah.edu/Courses/CS6967-F08/FE-notes.pdf
This is a really fun topic, and I wish you the best of luck! If you get stuck, just drop me a comment.
That rolling jelly cube video was made with Blender, which uses the Bullet physics engine for soft body simulation. The bullet documentation in general is very sparse and for soft body dynamics almost nonexistent. You're best bet would be to read the source code.
Then write your own version ;)
Here is a page with some pretty good tutorials on it. The one you are looking for is probably in the (inverse) Kinematics and Mass & Spring Models sections.
Hint: A jelly can be seen as a 3 dimensional cloth ;-)
Also, try having a look at the search results for spring pressure soft body model - they might get you going in the right direction :-)
See this guy's page Maciej Matyka, topic of soft body
Unfortunately 2d only but might be something to start with is JellyPhysics and JellyCar