Question by
afonsolfm · Jul 10, 2016 at 08:07 AM ·
2d-physics
Max velocity and constant acceleration
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
Your answer
Follow this Question
Related Questions
The problem with a circular 2D object (ball). 0 Answers
Why/How 2d tower of blocks collapse? 0 Answers
Enemy Movement With Physics (2D) 0 Answers
2D Dynamic Lights and Shadows 0 Answers
why does my 2d platformer lags? 1 Answer