How can I get a rigidbody velocity that I can make the value a float? Any help would be appreciated ![]()
3 Answers
3float speed = rigidbody.velocity.magnitude;
For example
float maxSpeed = 1.0f; // units/sec
void FixedUpdate() {
Rigidbody rb = GetComponent<Rigidbody>();
Vector3 vel = rb.velocity;
if (vel.magnitude > maxSpeed) {
rb.velocity = vel.normalized * maxSpeed;
}
}
the velocity is a vector3. call magnitude on it and it returns its length as float
I'm sorry. I'm kinda newbie. How exactly would I write that? I have this: PlayerBody.velocity.magnitude = CurrentSpeed;, but It gives me an error "property or indexer 'Vector3.magnitude cannot be assigned to -- it is read only"
– BrylosNot a problem my dude. Its an easy mistake to make. The worst ones are those kind where the error isnt where yoh think it is
– cbjuniorRigidbody.velocity is a Vector3 because it’s not only an Amount of speed, it’s also a Direction.
If you wanted an object move forward for example, you would apply the following:
using UnityEngine;
using System.Collections;
public class MovingObject : MonoBehaviour
{
public float m_speed = 20f;
private Rigidbody m_rigidbody;
void Start()
{
m_rigidbody = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
// Makes this object move forward at X speed.
m_rigidbody.velocity = m_speed * transform.forward;
}
}
To apply force in a different direction you would just change “transform.forward” to something else like, choose one to your liking:
m_rigidbody.velocity = m_speed * Vector3.up; // Move Up
m_rigidbody.velocity = m_speed * Vector3.left; // Move left
m_rigidbody.velocity = m_speed * Vector3.right; // Move right
m_rigidbody.velocity = m_speed * Vector3.back; // Move back
I hope that helps, I’m always around for further questions, best of luck!! @Brylos
Awesome dude! thanks a ton :D
– BrylosRemember that in some cases you might want to use sqrMagnitude instead of magnitude which is much faster to compute
– wiiiteekk