Hello.
I would like to move my character only in one direction at the time (only left, or only top etc). It works correctly but the problem is that when I move horizontally I can go up and down (by pressing W or S) while still pressing A or D (which is OK), but when I move vertically I have to stop pressing W or S to move left or right. I know why this is happening, but I don’t know how to fix that. Here is my code:
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour {
//Public variable to change speed of the player
public float MovementSpeed = 20f;
void Start () {
}
void Update () {
float forwardSpeed = Input.GetAxis("Vertical") * MovementSpeed;
float sideSpeed = Input.GetAxis("Horizontal") * MovementSpeed;
//This variables will be used to check whether player is pressing keys assigned to Horizontal and Vertical
bool statusHorizontal = Input.GetButton("Horizontal");
bool statusVertical = Input.GetButton("Vertical");
//By default character is not moving
Vector3 speed = new Vector3 (0, 0, 0);
//This is stupid, but in original Tanks 1990 player was able to move forward OR to the side
if (statusVertical == true)
{
speed.z += forwardSpeed;
}
else if (statusHorizontal == true)
{
speed.x += sideSpeed;
}
CharacterController cc = GetComponent<CharacterController> ();
cc.SimpleMove (speed);
}
}
Yes, I’m going something a 'la Tanks 1990 to learn Unity.
~Laran
Thank you, but this still don't satisfy me. Problem is that when I press A or D (Horizontal), then W or S (Vertical), then release Vertical (but still keep pressing Horizontal) my character is NOT moving. It works however when I "press Vertical > press Horizontal > release Horizontal" Tell me if I explained this badly:P "Me no Englando" :P
– LaranI added a minor tweak that fixes the issue you outline.
– robertbuThank you, but I have one more (silly) question. In line 29 there is: "If variable1 is true and variable2 (which is equal to variable1) is false, do something" I don't see any logic in this. For me it's like "if sun shines and sun does not shine, do something..."
– LaranTake a close look at the variable names. On is 'statusHorizontal' the second one is 'prevStatusHorizontal'. This code is testing for the change is state of statusHorizontal. So if in the previous frame statusHorizontal was false, and in the current frame it is true, then we set 'moveHorizontal' to true.
– robertbuOh wait... I completely forgot that this whole code is executed in every frame (so prevStatusVertical has value of previous frame, not current). This make sense now. You are great! (and I have a lot to learn :P)
– Laran