Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Is this the best way to read input, modify velocity and flip the character?

Discussion in 'Scripting' started by juanborgesv, Nov 30, 2018.

  1. juanborgesv

    juanborgesv

    Joined:
    Jul 15, 2017
    Posts:
    8
    I just started to create the Character Controller script for a 2D game. I was wondering if this is the appropiate way to manage the character's movement; read input in Update(), move the character in FixedUpdate(), and change the way the character is facing if needed in LateUpdate().

    I read this post asking about where it should read the input, if Update or FixedUpdate. So that's why I did it like below.

    I did a course on Coursera about Game Development, and the script provided has in LateUpdate() the steps to flip the character (using localScale) because "the Animator may override the localScale, this code will flip the player even if the animator is controlling scale". So If I am using the SpriteRenderer to flip the sprite, should I do it as below in the LateUpdate() or somewhere else?

    Code (CSharp):
    1. private void Update()
    2. {
    3.         _vx = Input.GetAxisRaw("Horizontal");
    4.         _vy = _rigidbody.velocity.y;
    5. }
    6.  
    7. private void FixedUpdate()
    8. {
    9.         _rigidbody.velocity = new Vector2(_vx * _moveSpeed, _vy);
    10. }
    11.  
    12. private void LateUpdate()
    13. {
    14.         if (_facingRight && _vx < 0)
    15.         {
    16.             _facingRight = false;
    17.             _spriteRenderer.flipX = true;
    18.         }
    19.         else if (!_facingRight && _vx > 0)
    20.         {
    21.             _facingRight = true;
    22.             _spriteRenderer.flipX = false;
    23.         }
    24. }