Question regarding Ridigbody2D.velocity.magnitude

Hi guys,

I’m currently trying to learn to build my own movement speed from scratch instead of relying on the Sample Assets provided by Unity.
Currently, I’m trying to cap the velocity of my rigidbody so it won’t get infinitely speedy.
Could someone tell me what is wrong with my Script?

using UnityEngine;
using System.Collections;

public class PlayerMovement : MonoBehaviour {

	public float moveSpeed = 30f;
	public float maxMoveSpeed = 50f;

	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
		if (Input.GetKey (KeyCode.LeftArrow)) {
						rigidbody2D.AddForce(Vector3.left * moveSpeed);
		}

		if (Input.GetKey (KeyCode.RightArrow)) {
			rigidbody2D.AddForce(Vector3.right * moveSpeed);
		}
	if (rigidbody2D.velocity.magnitude > maxMoveSpeed) {
						Rigidbody2D.velocity = Rigidbody2D.velocity.normalized * maxMoveSpeed;
				}
	}
}

If I understood the documentation correctly, rigidbody2d.velocity.magnitude reads the current force added to the velocity and I want the force to stay the same if the cap is reached and the button is held. Unity tells me "An object reference is required to access non-static member ‘UnityEngine.Rigidbody2D.velocity’

Big R, little r:

  • rigidbody2D is the rigidbody object attached to your GameObject
  • Rigidbody2D is the class which defines all such rigidbodies

A class defines an object, in the same way that a blueprint defines a building.

There may be functions associated with the Rigidbody2D class. For example, Vector3 provides helper functions like Distance, which have to do with vectors, but aren’t related to any specific vector.

On the other hand, the data specific to a particular rigidbody (such as its velocity) can only be accessed through that object.

So this line:

Rigidbody2D.velocity = Rigidbody2D.velocity.normalized * maxMoveSpeed;

Should read:

rigidbody2D.velocity = rigidbody2D.velocity.normalized * maxMoveSpeed;