# Roll a ball camera problem?

I use this official roll a ball code to move my ball:
Roll a ball

I changed the above code with this following code, which I found:
(EDIT: I found the link: Camera rotate)

``````// ADDED -- This will keep track of the direction your camera is looking
public Transform cam;

public float speed;

private Rigidbody rb;

void Start ()
{
rb = GetComponent<Rigidbody>();
}

void FixedUpdate ()
{
/*
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");

Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);

rb.AddForce (movement * speed);
*/

// CHANGED -- This limits movement speed so you won't move faster when holding a diagonal. It's just a pet peeve of mine
Vector2 inputDirection = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
if(inputDirection.sqrMagnitude > 1)
{
inputDirection = inputDirection.normalized;
}

// CHANGED -- This takes the camera's facing into account and flattens the controls to a 2-D plane
Vector3 newRight = Vector3.Cross(Vector3.up, cam.forward);
Vector3 newForward = Vector3.Cross(newRight, Vector3.up);
Vector3 movement = (newRight * inputDirection.x) + (newForward * inputDirection.y);

}
``````

Everything works, except, if I move back. Then the camera rotates 360 degrees. Forward, left and right works. Only back is not working.

Why? I can’t find the problem in the code.

I think, maybe there is a faster and better way to do this?

I may be wrong, but what I’m getting from all this is that you are rolling a ball, and you want the camera to follow the ball. It sounds as if you have the camera attached to the ball and have to counter the rotations to prevent the camera from spinning.

Maybe it would be a better idea to NOT attach the camera to the ball, but instead write a new CameraFollow script and in its update method, set the camera’s position relative to the ball’s position.

``````    public class CameraFollow : MonoBehavior
{
[Tooltip("The object to follow.")]
public GameObject FollowTarget;
[Tooltip("The offset applied to the targets position for setting the cameras final location.")]
public Vector3 PositionOffset;

public void Update()
{
var pos = FollowTarget.transform.position + PositionOffset;
transform.position = pos;
}
}
``````

NOTE: I wrote the code from scratch so it may not work 100% right out of the gate.