- Home /
using rb.MovePosition bugs the y position
I have a ball that has a rigidbody and a circle collider on it. I have the following script applied to it:
public class PlayerController : MonoBehaviour
{
[SerializeField] float speed = 400f;
Rigidbody2D rb;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
float move = Input.GetAxis("Horizontal") * Time.deltaTime * speed;
rb.MovePosition(rb.position + new Vector2(move, 0f));
}
}
The ball is in mid air in the scene. When I hit play, the ball falls but it doesn't fall quickly like it did without me writing "rb.MovePosition" method. What's the problem and how can I fix this?
Thanks
Answer by sean244 · Dec 29, 2018 at 04:46 AM
Try this
void FixedUpdate()
{
float move = Input.GetAxis("Horizontal") * speed;
rb.velocity = new Vector2(move, rb.velocity.y);
}
Since you're using a rigidbody operation, you don't need delta time. Also, you can now lower your speed to something much less, like 20f.
So when you’re working with rigidbody, you want to use FixedUpdate rather than Update. This is so that the physics operation will run the same across all devices, regardless of frame rate. As such, you no longer need to multiply the operation by delta time. We multiply certain operations like Transform.translate by delta time because we want them to be frame rate independent. But we’re dealing with a rigidbody operation that is being called in FixedUpdate, so it’s as if it’s already being multiplied by delta time behind the scenes. If you explicitly multiply it by delta time, then it’s like your multiplying it twice by delta time. This causes weird results. That’s why you needed to have such a high speed (400f) for your input to work.
@sean244 I know about the fixed update and stuff but what I don't understand is why you would use rb.velocity over rb.$$anonymous$$ovePosition and why rb.$$anonymous$$ovePosition is not working in my case. Sorry if I sound rude, I do apologize.
Your answer
Follow this Question
Related Questions
Rigidbody2D Normalizing only one axes 0 Answers
xsi to fbx model has inverted axis 0 Answers