Strange behaviour with adding and subtracting velocity in FixedUpdate?

I’ve ran into some strange behaviour when editing a Rigidbody2D’s velocity during fixed update. The idea is just to set a characters velocity and subtract it every fixed update to give a exact control over characters speed without effecting other forces on the character, how ever sometimes it gets ruined and the force is not subtracted. Here is the code:

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {
    /*
    By Tyler Perry.
    */
    [SerializeField]
    private float movementForce = 5f;
    private new Rigidbody2D rigidbody2D;
    private Vector2 force = new Vector2(0,0);

    void Start ()
    {
        rigidbody2D = GetComponent<Rigidbody2D> ();
    }
   
    void FixedUpdate ()
    {
        rigidbody2D.velocity -= force;
        force = new Vector3 (Input.GetAxis("Horizontal") * movementForce,0);
        Debug.Log ("" + force.ToString());
        rigidbody2D.velocity += force;
    }
}

I’m under the impression it should go:

-FixedUpdate
-Physics
-FixedUpdate
-Physics

And on and on forever at the same rate, how ever something must be going wrong… It also seems that gravity has something to do with the current velocity as well, I’m not sure how it works so I guess its just the way gravity works or something. I think it’s best to stick with MovePosition, but I’m still interested in why this happens.

The force you add and subtract can be the same but velocity changes because of drag and friction. If you use another variable to store the changes in force then you simply add (or assign) it to velocity you could have more predictable results. Perhaps… :slight_smile:

Why don’t you simply do this?

        void FixedUpdate ()
        {
            force = new Vector3 (Input.GetAxis("Horizontal") * movementForce,0,0);
            Debug.Log ("" + force.ToString());
            rigidbody2D.velocity += force;
        }