my sprint script is toggling? help please!
I am new to programming and trying to learn unity, I made this script to try and let the player move and sprint around, it mostly works except when I use shift to sprint it toggles and will not return to normal. I want your opinions on how to improve the script and how to fix the problem (i would also greatly appreciate some tips on how to improve). Thanks in advance, Tom.
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float speedF;
public float speedR;
public float sspeedF;
public float sspeedR;
void start(){
speedF = 10f;
speedR = 100f;
sspeedR = 150f;
sspeedF = 16f;
}
void Update()
{
if (Input.GetKeyDown(KeyCode.LeftShift)) {
speedF = sspeedF;
speedR = sspeedR;
}
if (Input.GetKeyUp (KeyCode.LeftShift)) {
speedF = speedF;
speedR = speedR;
}
var x = Input.GetAxis ("Horizontal") * Time.deltaTime * speedR; //rotation speed
var z = Input.GetAxis ("Vertical") * Time.deltaTime * speedF; // movement speed
transform.Rotate (0, x, 0);
transform.Translate (0, 0, z);
}
}
Answer by unity_1magvin1 · Nov 04, 2018 at 02:40 AM
The problem is simple.... when u hold shift u set the value of speedF to sspeedF and when u dont hold it u set the speed to itself.... which means it does this:
If u hold shft: speed = 16 (from 10 ) , if u dont gold it : speed = 16 ( from 16 )
I think instead of setting the value (=) , just add value ... like if (Input.GetKeyDown(KeyCode.LeftShift)) { speedF += sspeedF; speedR = sspeedR; } if (Input.GetKeyUp (KeyCode.LeftShift)) { speedF -= sspeedF; speedR = speedR; }