# Rotating a Sphere While Moving

Hello, it’s me again. I’ve been trying to figure out how to rotate a sphere when moving (think Marble Blast) Looking around I can’t seem to find anything and nothing I try seems to work.

Sorry for all the newbie questions

To figure out how much to roll a ball based on the distance traveled you calculate:

So you can then apply that to your ball like this:

``````float rotation = ((transform.position - oldPos).magnitude / ballRadius;

// Now to apply it
transform.RotateAround(transform.right, rotation);
``````

Note that this code assumes that you already rotated your ball to face the direction it’s moving in, like with a normal agent.

Then it just rotates to match the distance traveled.

Hope that helps!
-Jeremy

1 Like

I browsed around the Wiki a bit a found this script:

``````// These variables are for adjusting in the inspector how the object behaves
var maxSpeed = 7.000;
var force = 8.000;
var jumpSpeed = 5.000;

// These variables are there for use by the script and don't need to be edited
private var state = 0;
private var grounded = false;
private var jumpLimit = 0;

// Don't let the Physics Engine rotate this physics object so it doesn't fall over when running
function Awake ()
{
rigidbody.freezeRotation = false;
}

// This part detects whether or not the object is grounded and stores it in a variable
function OnCollisionEnter ()
{
state ++;
if(state > 0)
{
grounded = true;
}
}

function OnCollisionExit ()
{
state --;
if(state < 1)
{
grounded = false;
state = 0;
}
}

// This is called every physics frame
function FixedUpdate ()
{

// Get the input and set variables for it
jump = Input.GetButtonDown ("Jump");
horizontal = Input.GetAxis("Horizontal");
vertical = Input.GetAxis("Vertical");

// Set the movement input to be the force to apply to the player every frame
horizontal *= force;
vertical *= force;

// If the object is grounded and isn't moving at the max speed or higher apply force to move it
if(rigidbody.velocity.magnitude < maxSpeed  grounded == true)
{
rigidbody.AddForce (transform.rotation * Vector3.forward * vertical);
rigidbody.AddForce (transform.rotation * Vector3.right * horizontal);
}

// This part is for jumping. I only let jump force be applied every 10 physics frames so
// the player can't somehow get a huge velocity due to multiple jumps in a very short time
if(jumpLimit < 10) jumpLimit ++;

if(jump  grounded == true  jumpLimit >= 10)
{
rigidbody.velocity.y += jumpSpeed;
jumpLimit = 0;
}
}
``````

It works great except that while holding down the W key the ball rolls back and forth. What would I have to do to get the ball to roll forward in a straight line?

Any news?

Bump, since i could not find any solution for this either.

EDIT: Found it!

``````public var force:float = 1.0;

function FixedUpdate () {
var dir : Vector3 = Vector3.zero;

dir.x = Input.GetAxis("Horizontal");
dir.z = Input.GetAxis("Vertical");