I have a simple PlayerMovement script for a 2D platformer and I am attempting to limit left/right velocity to the float maxSpeed:
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
public float speed;
public float maxSpeed;
private Rigidbody2D rb;
void Start() {
rb = this.gameObject.GetComponent();
}
private void FixedUpdate() {
float x_movement = Input.GetAxis("Horizontal");
if(rb.velocity.magnitude < maxSpeed) {
Vector2 movement = new Vector2(x_movement, 0);
rb.AddForce(speed * movement);
}
}
void Update() {
if (rb.velocity.magnitude > 0)
Debug.Log(rb.velocity.magnitude);
}
}
-
"rb.velocity.magnitude < maxSpeed" in FixedUpdate() is the suggested method to limit velocity as per several tutorials and answers I have read here. However, this does not work. Via the Debug.Log statement in Update(), I can see that the value of rb.velocity.magnitude often exceeds maxSpeed. I assume this is due to FixedUpdate() not being called as often as frames are being rendered, meaning that my speed can exceed maxSpeed on any frames that FixedUpdate() is not being run.
-
I tried several alterations of this code, but what finally allowed me to limit the velocity to maxSpeed and maintain that speed while continuing to move were these changes in Update() and FixedUpdate():
private void FixedUpdate() {
float x_movement = Input.GetAxis("Horizontal");
if(rb.velocity.magnitude <= maxSpeed) {
Vector2 movement = new Vector2(x_movement, 0);
rb.AddForce(speed * movement);
}
}
void Update() {
rb.velocity = new Vector2 (Mathf.Clamp(rb.velocity.x, 0 - maxSpeed, maxSpeed), 0);
if (rb.velocity.magnitude > 0)
Debug.Log(rb.velocity.magnitude);
}
-
This does exactly what I want it to do as I can observe with Debug.Log, but it does not feel right to me. I am now essentially limiting the velocity in two places, in addition to using *both* AddForce and directly setting rb.velocity. Changing "rb.velocity.magnitude <= maxSpeed" to "rb.velocity.magnitude < maxSpeed" results in fluctuations in rb.velocity.magnitude once the maximum speed is reached (although not exceeding maxSpeed).
-
So, is my solution perfectly acceptable and I'm just being weird about it? Or is there a better solution?
↧