Simple balance using Physics

Hi there,

I’m fairly new to both Unity and C# but I’m having a fiddle with some physics just to practice and see where it goes. I’ve managed to use the arrow keys and simple AddRelativeForces to move a RigidBody player cube around but it seems to react quite badly to any little changes in the terrain, flipping and jumping about. I was hoping to set up a little ‘if’ method to automatically straighten the cube if it tipped too far but I’m guessing my logic is all off.

I’m open to any suggestions, even a key that just straightens the player, or maybe my problem is with the terrain or player properties? I’ve got the camera as a child of the cube, so it will follow it around.

(big apologies if this all doesn’t make sense, I started learning code a week ago :D)

Cheers

 using UnityEngine;
    using System.Collections;
    
public class PlayerDriver : MonoBehaviour {


	public float speed = 100;
	public float turnSpeed = 3;

	float tipped = ( != 1);

	// Balance to keep from flipping around
	void Balance() {
		if (transform.eulerAngles = new Vector3 (tipped, 0, tipped))
			transform.Rotate(Vector3.up, Time.deltaTime, Space.World);
		
	}
	
	// Update is called once per frame
	void FixedUpdate () {

	// controller using arrow keys
		if (Input.GetKey("up"))
			rigidbody.AddRelativeForce(Vector3.forward * speed);

		if (Input.GetKey("left"))
			rigidbody.AddTorque(0, -turnSpeed, 0);

		if (Input.GetKey("right"))
			rigidbody.AddTorque(0, turnSpeed, 0);

		if (Input.GetKey("down"))
			rigidbody.AddRelativeForce(Vector3.back * speed);
	
	}
}

A cube is flat with sharp edges, this sounds like realistic physical emulation, if you try to slide a cube over an ever so slightly rough surface in real life it will snag and flip out wildly. Wheels and spheres move over slightly uneven terrain far better. Having a very low friction physical material can help(Ice) but the problem remains that cubes are not spheres…
This is the reason that cars have wheels :slight_smile:

You increase angular drag or fix the rotation of your cube.