(C# Begineer) Small delay before moving

Hey guys, I’m trying to find a way to make my player move forward based on where its facing and I got it working. Only, I tried using the vertical axis input but using that for some reason causes a small delay before the player starts moving. The commented code below the if (vertical) is the code I’m currently using and it doesn’t give off delay. Still, I prefer the vertical axis one because I like to keep my code short. Any help will be appreciated :slight_smile:

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour
{
  public float playerSpeed;
  public float rotateSpeed;

  private Rigidbody2D player;

  void Start()
  {
    player = GetComponent<Rigidbody2D>();
  }

  void FixedUpdate()
  {
    // Movement
    float horizontal = Input.GetAxis("Horizontal");
    float vertical = Input.GetAxis("Vertical");

    if (vertical == 1)
    //if (Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.W))
    {
      player.transform.position += transform.up * playerSpeed * Time.deltaTime;
    }
    if (vertical == -1)
    //if (Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.S))
    {
      player.transform.position -= transform.up * playerSpeed * Time.deltaTime;
    }
    transform.Rotate(0, 0, horizontal * -rotateSpeed);

    Shoot(); // Shoot
  }

  void Shoot()
  {
    // Shooting code here
    if (Input.GetKey(KeyCode.Space))
    {
    Debug.Log("Bullet shot!");
    }
  }
}

First thing you should do is to move that code form FixedUpdate() to Update().

Input.GetAxis() returns a value in the range -1…1, so depending on your input you get get values different than 1 or -1 for some time, which may cause a delay you’ve mentioned.

You could also simplify the code (and fix the input values range issue if it was not intended), by writing:

player.transform.position += transform.up * playerSpeed *Time.deltaTime * vertical;

Instead of those two if(vertical…) statements.

1 Like

Thanks for the help! Though, I don’t need to move my code to Update(), it still works in FixedUpdate(). Anyways, thanks again for the useful informations :smile:

Input should always be handled in Update, not FixedUpdate.