- Home /
How can I tweak acceleration and deceleration of a Rigidbody2D with .AddForce()?
Hello, quite new to C# and Unity somewhat.
I want to make it so when a Horizontal input is pressed, my 2D character with a Rigidbody begins to slowly increase velocity until a speedCap is reached. If the Horizontal input is let go or if an oposite facing input is pressed while the character is running, make the velocity fall down back to 0.
The closest I've gotten to this is via .AddForce(). I've managed to implement a speedCap but unfortunately, I can't figure out how to tune certain aspects of AddForce's behavior, such as the acceleration (it reaches speedCap way too fast) and deceleration (takes too long for object to stop, and whenever the key is let go while the character is at full speed there's a quite noticeable "drag" effect).
{
// Configuration Parameters
[SerializeField] float speed = 5f;
[SerializeField] float speedCap = 15f;
// States
// Cached Component References Pt.1
Rigidbody2D myRigidbody;
Animator myAnimator;
Collider2D myCollider;
SpriteRenderer mySpriteRenderer;
// Declaring Variables
Vector2 movement;
// Start is called before the first frame update
void Start()
{
// Cached Component References Pt.2
myRigidbody = GetComponent<Rigidbody2D>();
myAnimator = GetComponent<Animator>();
myCollider = GetComponent<Collider2D>();
mySpriteRenderer = GetComponentInChildren<SpriteRenderer>();
}
// Update is called once per frame
void Update()
{
movement = new Vector2(Input.GetAxisRaw("Horizontal"), 0);
}
void FixedUpdate()
{
Move(movement);
if (myRigidbody.velocity.magnitude > speedCap)
{
myRigidbody.velocity = myRigidbody.velocity.normalized * speedCap;
}
}
// Methods
private void Move(Vector2 direction)
{
myRigidbody.AddForce(direction * speed);
}
}
I've read to mess around with my Object's Mass and Linear Drag on the inspector but its effects are quite pronounced; basically increasing any of both to anything above 2 makes my character almost immovable.
I'm open to any suggestions to achieving this besides using .AddForce(), much appreciated!