- Home /
How to maintain speed on the x axis according the last key pressed ?
Hi,
I'm trying to make a cube move on its x axis. The player gets to control the direction according his input (left arrow or right arrow) but I can't manage to maintain the movement even after he released the button.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float speed = 5f;
void FixedUpdate()
{
if (Input.GetKey(KeyCode.LeftArrow))
{
transform.Translate(-speed * Time.deltaTime, 0f, 0f);
}
else if (Input.GetKey(KeyCode.RightArrow))
{
transform.Translate(speed * Time.deltaTime, 0f, 0f);
}
}
}
here when I stop pressing the left or right arrow, the cube stops but I want it to keep moving (left or right) even after I release the button. Could you help me please ?
Answer by servo150 · Apr 20, 2020 at 12:13 PM
Not tested but should work
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float speed = 5f;
private float currentSpeed = 0f;
void FixedUpdate()
{
if (Input.GetKey(KeyCode.LeftArrow))
{
currentSpeed = -1f;
}
else if (Input.GetKey(KeyCode.RightArrow))
{
currentSpeed = 1f;
}
transform.Translate(-currentSpeed * Time.deltaTime, 0f, 0f);
}
}
Answer by BawerAgirman · Apr 22, 2020 at 12:12 PM
Oh god... it was that simple... Thanks a lot ! I appreciate your help
Your answer
Follow this Question
Related Questions
2D Platformer physics rotation Movement script - How to roll/flip a square on his edges ? 0 Answers
How can I make a unit fire in one direction while still moving in another? 1 Answer
Interrupt a MoveTowards when triggering 2 Answers
Move player in direction it's facing 1 Answer
how to make a block move in one direction,Make a Object such as a Block move in one direction 1 Answer