The question is answered, right answer was accepted
How to get rigidbody velocity?
How can I get a rigidbody velocity that I can make the value a float? Any help would be appreciated :)
Answer by ElijahShadbolt · Nov 11, 2016 at 01:32 AM
float 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;
}
}
Remember that in some cases you might want to use sqr$$anonymous$$agnitude ins$$anonymous$$d of magnitude which is much faster to compute
Just replace if statement with
if (vel.sqr$$anonymous$$agnitude > maxSpeed*maxSpeed) {
Answer by hexagonius · Nov 10, 2016 at 07:42 PM
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"
Answer by ThePersister · Nov 10, 2016 at 10:04 PM
Rigidbody.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
Follow this Question
Related Questions
Clamped position, but Velocity not stopping. 0 Answers
C# keep previous velocity while jumping, previous solutions not working 0 Answers
How can I move an object in the direction another object is facing. 1 Answer
Bullet shooting not working 0 Answers
Slow falling speed on player (with RB), but all other objects are fine (checked scaling). 0 Answers