x


How do I set max rigidbody velocity in C#?

This is my code:

using UnityEngine; using System.Collections;

public class Movement : MonoBehaviour {

public GameObject player;
public bool down;
public float forward = 15;
public float maxForward = 20;


void Start () {

}

void Update () {

    if (Input.GetKeyDown(KeyCode.RightArrow))
       down = true;
    if (Input.GetKeyUp(KeyCode.RightArrow))
       down = false; 

    if (down == true)
    {  
       player.rigidbody.AddForce(0,0,forward);
    }

    if (player.rigidbody.velocity.z > maxForward)
    {
       player.rigidbody.velocity.z = player.rigidbody.velocity.z.normalized;
       player.rigidbody.velocity.z *= maxForward;
    }

}

}

It does not work lol. Can someone tell me why & tell me how i can make this work? I want to set a maximum speed of a rigidbody sphere. Thanks! :D

more ▼

asked Nov 26 '11 at 07:02 AM

BioExtract gravatar image

BioExtract
31 6 8 8

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

You should use

player.rigidbody.velocity = Vector3.ClampMagnitude(player.rigidbody.velocity, maxForward);

That one line makes sure that the magnitude of the player's velocity cannot go above a certain value, however it does not limit specific axes.

Also, why don't you just use

if(Input.GetKey(KeyCode.RightArrow))
{
    player.rigidbody.AddForce(0,0,forward);
}

instead of all that messing around with 'down'? It does the same thing.

more ▼

answered Nov 26 '11 at 07:05 AM

syclamoth gravatar image

syclamoth
14.8k 7 15 80

Thanks! & I used the whole boolean down thing because i want the player to move if the key is being held down :)

Nov 26 '11 at 07:40 PM BioExtract

Yeah, but that's exactly what Input.GetKey does! There's no need to manage that manually.

Nov 27 '11 at 01:18 AM syclamoth
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x1781
x316
x18

asked: Nov 26 '11 at 07:02 AM

Seen: 2056 times

Last Updated: Nov 27 '11 at 01:18 AM