- Home /
Question by
JoshMBeyer · Mar 27, 2014 at 07:03 PM ·
rigidbodyrotatemove
How to rotate/move diagnal with rigidbody sphere
Having trouble with the physics here. I want the player(sphere game object) to be able to roll in every direction to navigate through the platform course. I can now go back and forth but trying to go to the side or diagnal isnt working properly here is the script. What am I doing wrong exactly?
UnityEngine;
using System.Collections;
public class SphereController : MonoBehaviour {
//The constant forward speed.
public float sphereSpeed;
//The user controlled left and right speed.
public float leftRightSpeed;
//Win or Loss.
public bool win;
public bool gameOver;
//The visual partical effect for when we collide.
//Just a cheap example.
public GameObject prefabVisual;
void Update ()
{
rigidbody.AddForce(Input.GetAxis("Horizontal"), 0, 0 * leftRightSpeed);
//transform.Rotate(new Vector3(0,Input.GetAxis("Horizontal"),0));
rigidbody.AddForce(0, 0, Input.GetAxis("Vertical") * sphereSpeed);
//Move forwards or backwards.
if (transform.position.z >= 19)
{
win = true;
//Disable movement of the sphere.
//Here we could load a different scene. Win screen, highscore screen, etc.
this.gameObject.GetComponent<SphereController>().enabled = false;
}
}
void OnCollisionEnter(Collision other)
{
//If we hit a obstacle.
if (other.gameObject.tag == ("Obstacle"))
{
//Tell us what we hit.
Debug.Log("Hit an obstical" + other.gameObject);
//gameOver = true;
//Instantiate the prefabVisual.
Instantiate(prefabVisual,transform.position,transform.rotation);
//Disable movement of the sphere.
this.gameObject.GetComponent<SphereController>().enabled = false;
//Make the sphere dissapear.
this.gameObject.GetComponent<MeshRenderer>().enabled = false;
//Could add a game over scene now.
}
}
}
Comment
Best Answer
Answer by T27M · Mar 27, 2014 at 07:20 PM
You have a few variables in the wrong place, make sure you set the values of sphereSpeed and leftRightSpeed in the inspector.
GetAxis returns either -1, 0, or 1. You are taking that value and multiplying it by your speed to move. Also check the FixedUpdate function, when dealing with forces it's recommended to use FixedUpdate.
//The constant forward speed.
public float sphereSpeed = 1;
//The user controlled left and right speed.
public float leftRightSpeed = 1;
// Update is called once per frame
void FixedUpdate () {
rigidbody.AddForce(Input.GetAxis("Horizontal") * leftRightSpeed, 0, 0);
rigidbody.AddForce(0, 0, Input.GetAxis("Vertical") * sphereSpeed);
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613141332im_/https://answers.unity.com/themes/thub/images/avi.jpg)