Space movement script

I made this 2D script that makes basic “space” movement, with rigidbody set to 0 gravity.
#pragma strict

var speed = 10;

function Start () {


function Update () {

if(Input.GetKey(KeyCode.LeftArrow)) {
rigidbody2D.AddForce (Vector3.left * speed);

if(Input.GetKey(KeyCode.UpArrow)) {
rigidbody2D.AddForce (Vector3.up * speed);

if(Input.GetKey(KeyCode.RightArrow)) {
rigidbody2D.AddForce (Vector3.right * speed);

if(Input.GetKey(KeyCode.DownArrow)) {
rigidbody2D.AddForce (Vector3.down * speed);


It works fine, but the problem is that there is no maximum speed. If you hold one of the arrow keys, it will just keep accelerating. So i want a new script that does the same as this one (try it out in a scene, with all rigidbody variables set to 0, and mass to 3) Where i can make maximum speed.

Ask me all the questions you have, if you dont understand what i mean, or need more info.

Maybe take a look at this question: How to limit “Force” speed (cumulative) without limiting Force

Basically just add a Mathf.Clamp after you AddForce.

rigidbody2D.AddForce (Vector3.up * speed);
rigidbody2D.velocity = Vector2.ClampMagnitude(rigidbody2D.velocity, speedLimit);

*Warning: I havent actually tested this myself so you might not be able to copy and paste this.

Speed is the magnitude of the direction vector.
SO speed is


If you want to see if your speed is greater then N you would say

if (rigid body.velocity.magnitude>N){
  //do smoething

Now, a normalized vector is a vector with a magnitude of 1. SO velocity in your current direction with a speed of 1 is


If you multiply a normalized vector with a single value (a Scalar, in math terms) you get a vector in the direction of the normalized vector at the magnitude of the Scalar.

SO… putting that all together. To make sure you go no faster the N you say…

if (rigid body.velocity.magnitude>N){
   rigidbody.velocity = rigibody.velocity.normalized * N;


(1) This is for 3D use the appropriate 2D structures instead for 2D

(2) This code uses magnitude to check distance not magnitude-squared for clarity. In most systems magnitude-squared would be more efficient, however other people’s test of Unity have suggested that vector magnitude is cached in such a way that there is no speed loss for using it instead.