How to Limit or Remove Acceleration with RigidBody2D?
This is the only method of movement that I can get to work and I would rather not have acceleration but I'm stuck with it for now... How can I limit the acceleration so it doesn't accelerate infinitely or better yet remove acceleration altogether WITHOUT scraping this method of movement?
using UnityEngine;
using System.Collections;
public class SimpleMovement : MonoBehaviour
{
public Vector2 thrustBackward;
public Vector2 thrustForward;
public Vector2 thrustUp;
public Rigidbody2D rb2D;
void Start ()
{
thrustBackward = new Vector2 (-10, 0);
thrustForward = new Vector2 (10, 0);
thrustUp = new Vector2 (0, 10);
rb2D = GetComponent<Rigidbody2D> ();
}
void Backward ()
{
rb2D.AddForce (thrustBackward, ForceMode2D.Force);
}
void Forward ()
{
rb2D.AddForce (thrustForward, ForceMode2D.Force);
}
void Jump ()
{
rb2D.AddForce (thrustUp, ForceMode2D.Impulse);
}
void Update ()
{
if (Input.GetKey (KeyCode.LeftArrow))
Backward ();
if (Input.GetKey (KeyCode.RightArrow))
Forward ();
if (Input.GetKeyDown (KeyCode.UpArrow))
Jump ();
}
}
Answer by AurimasBlazulionis · Oct 28, 2016 at 09:00 PM
You can limit velocity. Inside update loop or fixed update loop add a line similar to this: rb2D.velocity = new Vector2(Mathf.Clamp(rb2D.velocity.x, -maxSpeed, maxSpeed), Mathf.Clamp(rb2D.velocity.y, -maxSpeed, maxSpeed));
. Just change maxSpeed variables anyhow you like. It will limit speed of the object.
You should probably apply force in FixedUpdate loop by the way (except keep jump in the regular update loop to prevent input issues), because Update is inconsistent.