# How to roll a ball along a curved tube.

I am developing a slalom game. I have a ball rolling over a tube, it can rotate all around the edge of the tube. So far the ball will constantly roll forward. The problem is that at some point there will be a turn in the tube I have no clue how to have the ball turn with the turn section. I can’t just do look at because it won’t smoothly turn and the turn piece can be at any angle. The control script is below and has its own problems here: http://answers.unity3d.com/questions/369543/quirky-unasked-for-rotation-with-ridigidbodies.html I’ve also included a picture of the turn, in this case the ball will be rolling down and to the right. Any ideas?

``````var rot;
var tube : Transform;
function Start(){
}
function FixedUpdate () {
rot = Input.GetAxis("Horizontal") * -10;
if(rot != null && tube != null){
Debug.Log("working");
transform.RotateAround(tube.position, Vector3.forward, rot);
}
else{
}
rigidbody.AddForce((tube.position - transform.position) * 5 * Time.smoothDeltaTime);

}
function OnCollisionEnter(collision : Collision){
if(collision.transform.tag == "tube"){
tube = collision.transform;
}
}
``````

[6094-screen+shot+2012-12-26+at+8.22.24+pm.png|6094]

Here’s how to do it !

Notice the “coin” …

The “coin” would be invisible. But make it visible at first, so you can see what you are doing.

The “coin” would be the same diameter as the tube. But at first make it 10% bigger so you can see it clearly. It will peek out of the tube.

Notice the “coin” has the small ball attached to it.

Notice the “FORWARD” direction (arrow) of the “coin”.

As the “coin” moves through the tube:

The FORWARD direction must always match the forwards direction in the tube at any differential - in other words, the tangent of the centerline at any point.

(Indeed - this is how you define a tube! By sweeping out a surface using a circle.)

To make the user steer “left and right” just rotate the coin (of course, rotate it around it’s FORWARD axis).

Code requirements: need the centerline of the tube. Need a line of code that moves the coin along the centerline. Need a line of code that sets the FORWARD to the current tube tangent.

So that’s probably the easiest way to do it! This is flawlessly mechanical - recall that the way you produce a tube is by sweeping out a circle in space - so the SmallBall will always be exactly on the surface. Happy new year!

Can you read out the normal of your collisionpoint and apply a force in the opposite direction? then it should alway stick to the surface instead of rotating around the tube. your asset looks fairly ‘highpoly’ so it should look smooth enough