I have a problem , I want to make an object move left when the “A” key is pressed but stop moving left the the “A” key isn’t pressed( and the same for the right key, “D”).
Here’s the code I have at the moment:
function Update () {
if(Input.GetButtonDown("D")){
Left = false;
Right = true;
}
if(Input.GetButtonDown("A")){
Left = true;
Right = false;
}
if (Left == true){
transform.Translate (Vector3(20,0,0) * Time.deltaTime *Speed);
}
if (Right == true){
transform.Translate (Vector3(-20,0,0) * Time.deltaTime*Speed);
}
}
How could I modify this code to do what I want it to do?
You should really be using Input.GetAxis(“Horizontal”) instead and get rid of the redundant if statements.
Ignoring that, with your current code you can use Input.GetButtonUp to set your variables to false when the appropriate key is no longer being held down.
I don’t understand if your problem is being locked to the x-axis or your object continuing to move after the key, if it’s the first then I’m sorry :(. This is a quick fix; but it’s not ideal.
function Update () {
if(Input.GetButtonDown("D")){
Left = false;
Right = true;
}
if(Input.GetButtonUp("D")){
Right = false;
}
if(Input.GetButtonDown("A")){
Left = true;
Right = false;
}
if(Input.GetButtonUp("A"))
{
Left = false;
}
if (Left == true){
transform.Translate (Vector3(20,0,0) * Time.deltaTime *Speed);
}
if (Right == true){
transform.Translate (Vector3(-20,0,0) * Time.deltaTime*Speed);
}
}
Thanks both of you! . Brotherhood explained it in terms of “here’s what you should do”. DxCam1 explained it in terms of “Here’s the physical code”.
I learnt off both of you , thanks!