- Home /
Click button to switch between "this" function and "that" function
So this is still my first week trying to write code for a simple game I thought of, so sorry if the question sounds dumb or is answered in documentation.
So I have this character that moves with WASD, but when I press something (in this case, button I) I want the WS to move him horizontally and AD to move him vertically. Basically swapping the vertical and horizontal.
EDIT: figured out I don't need 4 types of floats. stupid me.
void Update () {
float vertical = Input.GetAxis("Vertical") * VerticalSpeed;
float horizontal = Input.GetAxis("Horizontal") * HorizontalSpeed;
Vector3 MoveDirection;
MoveDirection = new Vector3(horizontal, 0, vertical);
if (Input.GetKey(KeyCode.I))
{
MoveDirection = new Vector3(vertical, 0, horizontal);
}
But I have to hold the I for the swapping to work and that's not what I wanted. GetKeyDown and GetKeyUp don't help either.
Can anyone help me?
Answer by hectorux · Jun 28, 2018 at 11:01 PM
You can try this under your vector3 MoveDirection.
if(Input.GetKeyDown(KeyCode.I) && !pressed){
normalBehaviour=!normalBehaviour;
pressed=true;
}
if(Input.GetKeyUp(KeyCode.I)){
pressed=false;
}
if(normalBehaviour){
MoveDirection = new Vector3(horizontal, 0,vertical);
}else{
MoveDirection = new Vector3(vertical, 0, horizontal);
}
hm that's weird, I'm using visual studio and it's not accepting "pressed" and "normalBehaviour". Do I have to declare them first?
Actually I think i fixed it! I declared normalBehaviour as bool and get rid of pressed. now it looks like this
if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.I))
{
normalBehaviour = !normalBehaviour;
}
if (normalBehaviour)
{
$$anonymous$$oveDirection = new Vector3(vertical, 0, horizontal);
}
else
{
$$anonymous$$oveDirection = new Vector3(horizontal, 0, vertical);
}
actually it's weird because when normalbehaviour is true the vector3 should be horizontal, 0, vertical but it's acting otherwise, so I had to swap them like above for it to work.
EDIT: stupid me. I declared normalBehaviour = true and now it works perfect.