Question by
Donovan26BA · Jan 17, 2020 at 11:02 PM ·
player movementupdate functionkeypressincrement
How to limit the amount of key presses that are read in the Update function?
I hope my question makes sense. I'm an absolute beginner
I have a simple game where you push the left or right arrow to dodge oncoming obstacles. The player then moves in a set increment either left or right at a set speed.
The problem is that if the keys are pushed rapidly, alternating left or right quickly, the player starts moving at different increments and it seems as though the game can't keep up with the rapid button presses. It seems as if the next button press is read and the player moves again before they've reached the end of the first move, which offsets the increment.
Is there a way to only read the button press once the player has reached the end of the first move. Am I doing something wrong? Please help!
private Vector3 targetPos;
public float Xincrement; //increment that the player moves left or right, set to 3
public float speed;
public float maxLeft; //set to -3
public float maxRight; //set to 3
void Update()
{
transform.position = Vector3.MoveTowards(transform.position, targetPos, speed * Time.deltaTime);
if (Input.GetKeyUp(KeyCode.LeftArrow) && transform.position.x > maxLeft)
{
targetPos = new Vector3(transform.position.x - Xincrement, transform.position.y, transform.position.z);
}
else if (Input.GetKeyUp(KeyCode.RightArrow) && transform.position.x < maxRight)
{
targetPos = new Vector3(transform.position.x + Xincrement, transform.position.y, transform.position.z);
}
//Vector3 pos = transform.position;
//pos.x = Mathf.Clamp(pos.x, -3, 3);
//transform.position = pos;
}
}
Comment