0
\$\begingroup\$
 void Movement()
{
    transform.Translate(Vector3.forward * 10 * Time.deltaTime);

    if(Input.GetKey(KeyCode.S))
    {
        transform.Translate(Vector3.forward * 3 * Time.deltaTime);
    }

    if(Input.GetKeyUp(KeyCode.S))
    {
        transform.Translate(Vector3.forward * 10 * Time.deltaTime);
    }
}

I tried this code but seems to me, it didn't work as I expected it to.

What I expect:

  • my character moves along at a speed of 10 automatically

  • when the S key is held, the character slows down to a speed of 3 instead

  • when the S key is released, the character goes back to their default speed of 10

What I observe:

  • the character does not slow down when the S key is pressed

How can I fix this?

\$\endgroup\$
0

1 Answer 1

0
\$\begingroup\$

It looks like you're trying to switch between two speeds: 10 when no key is pressed, and 3 when the S key is pressed. (S for "Slow"?)

The trouble is that the first line of your function has already moved the object at speed 10, no matter what the state of the keys might be. Then if S is pressed/held, you move again at speed 3, for a total movement of speed 13! So you sped up instead.

Lastly, if the S key was released this frame, you move again at speed 10, in addition to the movement at the start of the function, giving you a momentary burst of 20 speed just as the key is released.

A clearer way to write what it looks like you mean would be...

// Expose Inspector variables for clarity and ease of tuning, 
// rather than "magic number" constants you need to edit in code.
public float fastSpeed = 10f;
public float slowSpeed = 3f;

void Update() {
    // By default, use the fast speed.
    float currentSpeed = fastSpeed;

    // But if the player has the S key held, choose the slow speed instead.
    if(Input.GetKey(KeyCode.S))
        currentSpeed = slowSpeed;

    // Move at the chosen speed.
    transform.Translate(0, 0, currentSpeed * Time.deltaTime);
}
\$\endgroup\$
1
  • \$\begingroup\$ Thank you so much! so what you meant is i just give my character a boost speed without me acknowledging it haha. thank you soo much my brother \$\endgroup\$ May 26, 2020 at 13:38

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .