# Calculate speed from rigid body in a 3d space sim

Hi everyone,

I am trying to learn c# as I come from a design background in games and think it’s important to understand the basics. Anyway… I decided to make a simple 3d space sim to do this.

I am currently trying to calculate speed to feed into an NGUI filled sprite but unsure how to do this.

What I did was to use: `speed = rigidbody.velocity.x;` I quickly found out that this only gets speed in the x axis which is no good for a space sim.

I then tried:

``````speedX = rigidbody.velocity.x;
speedY = rigidbody.velocity.y;
speedZ = rigidbody.velocity.z;
speed = speedX + speedY + speedZ;
``````

this sort of worked but only going forward in the axis’ as the number would go into minus figures as soon as I rotated the ship and travelled in the other direction.

Any help would be greatly appreciated.

Thank you

Use Mathf.Abs() to get the magnitudes of your velocities. `speedX = Mathf.Abs(rigidbody.velocity.x);`

the absolute speed (length of the vector) can be obtained by rigidbody.velocity.magnitude. this is direction independent. summing up the directional parts of the vector does NOT get you the overall speed but a more or less meaningless value.

By the way, the magnitude of the resultant vector with Vx,Vy, and Vz components is sqrt(Vx^2 + Vy^2 + Vz^2). That’s the resultant speed, or magnitude of the velocity.

You could also just use rigidbody.velocity.magnitude to do it the easy way

(rigidbody.velocity gives all three components in Vector 3 format)

Also, what are you trying to do exactly? I’m sure one of us know a more efficient way of doing this that doesn’t need additional side calculations… I think.

Thanks everyone. Thats really helpful. I was trying to get the speed of the spaceship so that I could feed it into a GUI HUD that I have designed.

I also knew that adding the velocities together wouldn’t work but wanted to see what the result would be from a learning point of view.

Thanks again

rigidbody.velocity.magnitude worked perfectly. Thank you