- Home /
Question by
afonsolfm · Jul 10, 2016 at 12:12 PM ·
rigidbody2daddforce2d-physicsforce
Acceleration and Max Speed on 2D Object
Basically I want to control the acceleration and max speed for an object.
The max speed should be constant for all objects of a type, but the acceleration should be different for objects with different masses.
Should I make a variable for acceleration per unit of mass ?
Here's what I've got so far, and it's working pretty well.
public class PlayerController : MonoBehaviour {
public float maxSpeed = 5f; // 5 m s^-1
public float acceleration = 10f; // 10 m s^-2
private Rigidbody2D rb2d;
void Start()
{
rb2d = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
if (rb2d.velocity.magnitude > maxSpeed)
rb2d.velocity = rb2d.velocity.normalized * maxSpeed;
float horizontal = Input.GetAxis("Horizontal") * acceleration * Time.deltaTime;
float vertical = Input.GetAxis("Vertical") * acceleration * Time.deltaTime;
rb2d.AddForce(new Vector2(horizontal, vertical), ForceMode2D.Impulse);
print(rb2d.velocity.magnitude);
}
}
Comment