how to move Rigidbody using A and D keys

Hi

How would I go about moving a Rigidbody cube left(key a) or right (key d).

I can see that it will have something to do with AddRelativeForce or AddForce but how to you access the key pressed.

I’m very new to all this :slight_smile: if you could point me in the right direction (info on forum or Unity documents) that you be great :slight_smile:


I found this in the documents - it is OK to use with Rigidbody?

var speed = 10.0;
var rotationSpeed = 100.0;

function Update () {
// Get the horizontal and vertical axis.
// By default they are mapped to the arrow keys.
// The value is in the range -1 to 1
var translation = Input.GetAxis (“Vertical”) * speed;
var rotation = Input.GetAxis (“Horizontal”) * rotationSpeed;

// Make it move 10 meters per second instead of 10 meters per frame…
translation *= Time.deltaTime;
rotation *= Time.deltaTime;

// Move translation along the object’s z-axis
transform.Translate (0, 0, translation);
// Rotate around our y-axis
transform.Rotate (0, rotation, 0);
}

You can check for key events via the Input class, specifically either GetKey or GetKeyDown.

Yes, and no. The code you cited would be ok to start with for non-rigidbodies, but not for rigid ones. If you’re going to use rigidbodies then:

  1. Use FixedUpdate, not Update nor LateUpdate.

  2. Use rigidbody.AddForce() to move the object based on key presses.

If you’re not using rigidbodies then:

  1. Feel free to use Update or LateUpdate, but not FixedUpdate.

  2. Use transform.translate to move the object based on key presses.

Hope that helps!

Hi HiggyB

Thanks so much for your help and it does help :slight_smile: you rock.