- Home /
How to determine speed of an object when using transform.position
Hi, I am using the following code to rotate and move the player
float cameraSmooth = 5.0f;
float modX;
float modZ;
float moveSpeed = 50.0f;
modX = Input.GetAxis("Horizontal") * Time.deltaTime * moveSpeed;
modZ = Input.GetAxis("Vertical") * Time.deltaTime * moveSpeed;
modifier.z = modZ;
modifier.x = modX;
transform.position = Vector3.Lerp(transform.position, transform.position + modifier, Time.deltaTime * cameraSmooth);
var inputZ = Input.GetAxis("Vertical");
var inputX = Input.GetAxis("Horizontal");
var angle = Mathf.Atan2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0, angle, 0);
The problem I have is that I need to determine the speed of the object to affect animation speed.
I cant use the joystick axis as it goes from -1 to +1 and I cannot use rigidbody.velocity.magnitude as I am not using forces.
Is there any way I can work out the speed of the object from a scale of 0 to 1?
Answer by MakinStuffLookGood · Jan 22, 2015 at 09:13 PM
You can't use the joystick because it goes from -1 to 1? Could you not just use Mathf.Abs(Input.GetAxis("Horizontal"))
to get a value in the correct range then?
If that's no good, just store your position every frame in some variable Vector3 prevPosition
and each frame you can do something like:
float instantaneousSpeed = Vector3.Distance(transform.position, prevPosition);
Thanks Broxxar, I created the following and it works great :)
float x = $$anonymous$$athf.Abs(inputX);
float z = $$anonymous$$athf.Abs(inputZ);
float s = $$anonymous$$athf.$$anonymous$$ax(z, x);
Answer by carrollh · Jan 22, 2015 at 08:07 PM
Since you have a rigidbody, why don't you just use Rigidbody.MovePosition and Rigidbody.MoveRotation? Then I think you could use the rigidbody.velocity.magnitude that you mentioned. You might need to normalize it first to get it into unit vector form. So your code might look like this:
rigidbody.MovePosition(rigidbody.position + moveSpeed * Time.deltaTime);
float velMag = rigidbody.velocity.magnitude;
animator.SetFloat("Speed", velMag / moveSpeed);
Hey thanks for helping! I tried that but when I put vel$$anonymous$$ag to Debug.Log its always showing 0
Any ideas?
Your answer
Follow this Question
Related Questions
collider triggers transform position 1 Answer
How do I change one value of a vector? 2 Answers
Trouble converting transform.position to C# 1 Answer
fixed distance for Vector3.moveTowards ? 1 Answer
why one works, the other does not 2 Answers