Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Join us on March 30, 2023, between 5 am & 1 pm EST, in the Performance Profiling Dev Blitz Day 2023 - Q&A forum and Discord where you can connect with our teams behind the Memory and CPU Profilers.
    Dismiss Notice

Question Why is my movement jittery?

Discussion in 'Scripting' started by Not_Sure, Mar 19, 2023.

  1. Not_Sure

    Not_Sure

    Joined:
    Dec 13, 2011
    Posts:
    3,506
    I'm sure it's a update vs fixedupdate problem, but I cant figure out why.

    Code (CSharp):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5. public class PlayerMovement : MonoBehaviour
    6. {
    7.     [SerializeField] float walkSpeed, runSpeed, crawlSpeed, airAcceleration, groundAcceleration, differentialAcceleration, differential, currentSpeed, targetSpeed;
    8.     PlayerState playerState;
    9.     Rigidbody myRigidbody;
    10.     bool isFacingRight;
    11.     // Start is called before the first frame update
    12.     void Start()
    13.     {
    14.         isFacingRight = true;
    15.         myRigidbody = GetComponent<Rigidbody>();
    16.         playerState = GetComponent<PlayerState>();
    17.        
    18.     }
    19.     private void Update()
    20.     {
    21.         targetSpeed = Input.GetAxis("XMovement");
    22.         if (playerState.isCouching) targetSpeed = targetSpeed * crawlSpeed;
    23.         if (!playerState.isCouching && !playerState.isRunning) targetSpeed = targetSpeed * walkSpeed;
    24.         if (!playerState.isCouching && playerState.isRunning) targetSpeed = targetSpeed * runSpeed;
    25.     }
    26.     // Update is called once per frame
    27.     void FixedUpdate()
    28.     {
    29.         currentSpeed = targetSpeed;
    30.         Vector3 applyMovement = new Vector3(currentSpeed, 0, 0);
    31.         applyMovement = applyMovement * Time.fixedDeltaTime;
    32.         applyMovement += myRigidbody.position;
    33.         myRigidbody.MovePosition(applyMovement);
    34.     }
    35. }
    36.  
    I've tried moving the inputs to the fixed update, but it still jitters.

    EDIT: It seems to have issues in certain areas, not everywhere. From 0 to 8 on the x plane it jitters, and everything after is smooth.
     
    Last edited: Mar 19, 2023
  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    4,022
    Have you made sure to set your rigidbody to Interpolate?
     
    Not_Sure likes this.
  3. Not_Sure

    Not_Sure

    Joined:
    Dec 13, 2011
    Posts:
    3,506
    That was it.

    Thanks!