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);
rb.AddForce(movement * speed);
}
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?