Hey guys,
I am trying use space to change the directions of my character and it doesn’t some to be working. I’m trying to make the player go left or right by pressing space depending on the current direction of the player. Ex. If I am going left and I press space, I change directions and I go right. If I’m going right and I press space, I change directions and go left.
This is my current script for player movement
private var movement : int = 50;
function Update () {
//Left Movement
if (Input.GetKeyDown(“space”) == true && movement == 50){
movement = -50;}
//Right Movement
if (Input.GetKeyDown(“space”) == true && movement == -50){
movement = 50;}
transform.Rotate(Vector3(0,movement,0) * Time.deltaTime);
//Forward Movement
transform.Translate(Vector3(20,0,0) * Time.deltaTime);
Debug.Log(movement);
}
Your first “if” sets the movement to -50, so the next if’s condition is also true and sets it back to 50.
Try this:
private var movement : int = 50;
function Update () {
if (Input.GetKeyDown("space") == true) {
if(movement == 50){ //Left Movement
movement = -50;
} else { //Right Movement
movement = 50;
}
}
transform.Rotate(Vector3(0,movement,0) * Time.deltaTime);
//Forward Movement
transform.Translate(Vector3(20,0,0) * Time.deltaTime);
Debug.Log(movement);
}
Also note that youre rotating every frame, is that really what you want? Rotate 50 degrees in 1 second on y?
Maybe you should rotate only when the Space key was pressed (then setting the rotation directly would work better), or check some other condition like pointing a certain direction (maybe you need to check this function too: Unity - Scripting API: Vector3.RotateTowards)