weird float problem
I was using this simple script
public float speed = 1f;
public Rigidbody rb;
// Update is called once per frame
void Update()
{
float xMov = Input.GetAxisRaw("Horizontal");
float zMov = Input.GetAxisRaw("Vertical");
rb.velocity = new Vector3(xMov, rb.velocity.y, zMov) * speed;
}
It works just fine, but when I want to increase the speed to more than 1, it gives me this error as soon as I move
can someone help me, been trying to fix this problem for about a week now.
Answer by Eno-Khaon · Dec 27, 2021 at 05:28 AM
Aside from the fact that you're updating your velocity out of sync with physics updates (setting Rigidbody.velocity during Update() rather than FixedUpdate()), the main problem here is that you're accelerating on the Y-axis on every Update() cycle.
If we cut out the rest, you're doing this:
rb.velocity = new Vector3(0f, rb.velocity.y, 0f) * speed;
Now, let's say your "speed" is set to 5:
current Y-axis speed per Update():
frame# | Y speed
-------+--------
0 | 1
1 | 5
2 | 25
3 | 125
4 | 625
5 | 3125
As you can see, within a single second (60 frames, in this case), your Y-axis speed would accelerate to ~8.6e41 times what it started at with a "speed" value of 5.
If we ignore the fact that directly setting velocity like this isn't the ideal approach to movement, the simple fix for this would be to only multiply the relevant values by your speed:
rb.velocity = new Vector3(xMov * speed, rb.velocity.y, zMov * speed);
Your answer
Follow this Question
Related Questions
Argument `#1' cannot convert `float' expression to type `UnityEngine.Vector3 ? 1 Answer
Can I compare a Transform variable (x, y, z) against float variables? 1 Answer
Object and Transform box misalign when moving away from 0.0.0. 0 Answers
Position Child Object to center of Parent Object [SOLVED] 1 Answer