Hey guys, I’m new to Unity and C# so still learning, but wanted to query here on the best way to achieve this?
Here is my current movement script - no doubt there are better ways to code movement (and I imagine I will learn these and time goes on) but I’m struggling to find a way to make my character speed up and then slow down again once shift is no longer held.
Here is my current script
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
public Rigidbody rb;
public float MoveSpeed;
public float UpSpeed;
public float shiftSpeed;
// Update is called once per frame
void Update()
{
Physics.gravity = new Vector3(0, -120f, 0);
if (Input.GetKey(“w”))
{
rb.AddForce(0, 0, MoveSpeed * Time.deltaTime, ForceMode.VelocityChange);
}
if (Input.GetKey(“s”))
{
rb.AddForce(0, 0, -MoveSpeed * Time.deltaTime, ForceMode.VelocityChange);
}
if (Input.GetKey(“a”))
{
rb.AddForce(-MoveSpeed / 50, 0, 0 * Time.deltaTime, ForceMode.VelocityChange);
}
if (Input.GetKey(“d”))
{
rb.AddForce(MoveSpeed / 50, 0, 0 * Time.deltaTime, ForceMode.VelocityChange);
}
if (Input.GetKeyDown(“space”))
{
rb.AddForce(0, UpSpeed, 0 * Time.deltaTime);
}
if (Input.GetKey (“left shift”))
{
MoveSpeed = shiftSpeed;
}
}
MoveSpeed is set at 100 and shiftSpeed is at 150
When I press shift in game-play, the player does speed up, but then stays at 150 without changing back to the normal move-speed once shift is no longer held.
Is there a way to make this work with the current code i have?
I have tried an else statement - else {MoveSpeed = 100f;} - but then my character just stays at 100 speed despite pressing shift.
I would appreciate any advice.
Thankyou