How to make my float return to it's original value after being changed.
So I have a movement script here and I want it to make it so when I press the left control key it cuts the movement speed in half. The code I have here does do that but when I let go of the left control key it leaves the slowed float at 0.5. I'm really new to programming and I can't figure out a way to make the value easily return back to 1 when the key is not pressed. I have my code below just so you guy's can see everything that's going on.
using UnityEngine;
using System.Collections;
public class PlayerControl : MonoBehaviour
{
public float movementSpeed = 1.5f;
public float slowed = 1f;
void Update () {
if(Input.GetKey(KeyCode.UpArrow))
{
this.transform.Translate(new Vector2(0,1) * (movementSpeed * slowed) * Time.deltaTime);
}
if (Input.GetKey(KeyCode.DownArrow))
{
this.transform.Translate(new Vector2(0,-1) * (movementSpeed * slowed) * Time.deltaTime);
}
if (Input.GetKey(KeyCode.LeftArrow))
{
this.transform.Translate(new Vector2(-1,0) * (movementSpeed * slowed) * Time.deltaTime);
}
if (Input.GetKey(KeyCode.RightArrow))
{
this.transform.Translate(new Vector2(1,0) * (movementSpeed * slowed) * Time.deltaTime);
}
if (Input.GetKey(KeyCode.LeftControl))
{
slowed = 0.5f;
}
}
}
Answer by Knnthra · Dec 16, 2015 at 07:25 AM
This can be done a lot easier, but I understand that you are learning. However an easy fix for you would be to use:
if (Input.GetKeyDown(KeyCode.LeftControl))
{
slowed = 0.5f;
}
if (Input.GetKeyUp(KeyCode.LeftControl))
{
slowed = 1;
}
No, I want the speed to be slowed by half when I press control and changing it to left shift will not change anything. it's just when the code here is run if (Input.Get$$anonymous$$ey($$anonymous$$eyCode.LeftControl)) { slowed = 0.5f; }
It changes the float called slowed to 0.5 but it does not change back to 1 when I let go of the key.
I just mistook shift from control when I wrote the answer. Check my update on the answer. I know changing control to shift doesn't change anything. Notice that I'm using getkeydown ins$$anonymous$$d of getkey
Oh sorry. I misread the code. Thanks alot this worked.