Hi, I'm trying to decrease the speed of my bike , when the "W" key is up. Variables : Code (csharp): var Speed : float; var Acceleration : float = 0.1; var MaxSpeed : int = 13; var MinSpeed : int = -3; For the acceleration I have this : Code (csharp): if(Input.GetKey("w") (Speed < MaxSpeed )){ Speed = Speed + Acceleration; } So the bike is slowly speeding up , but I don't know how to make it slow down gradually when the "w" key isn't pressed,(Input.GetKeyUp("w")). Any help would be brilliant, Thanks Hawx
Speed = Speed - Acceleration? Also, you should really be factoring delta time into movement. It is the best way to assure the same speed on all types of pcs (frame independent)
I've tried that but GetKeyUp only returns once , so it only minus' 0.1 from speed. I've been looking for a different method. New Variable (for when the bike stops. : Code (csharp): var NeutralSpeed : int = 0; Here's the code for key up: Code (csharp): if(Input.GetKeyUp("w") (Speed > NeutralSpeed )){ Speed = Speed - Acceleration; } Thanks , Hawx
Its because GetKeyUp is only called once and therefore your speed will only subtract the acceleration one time. You need to set a variable lets say a boolean to be true when the key is up to start the deceleration. then in your update you will check to see if deceleration is true and that your not already stopped and then you would continue with the speed - acceleration.. hope this makes sense
Possibly something simple like this would be a good base to work from? Code (csharp): if(Input.GetKey("w") ) { if(Speed < maxSpeed) Speed += Acceleration; } else { if(Speed > 0) Speed -= Acceleration; } GetKey returns true while the player holds the key down. Therefore, when they stop holding it down it will be false and your speed can decrease GetKey
Thanks guys! Both of these make sense, so I will try both of them. Thanks a lot! Hawx Note : Thanks for both of your inputs , I've ended up using what Mister-E2 put and have moved this: Code (csharp): var transAmount = Speed * Time.deltaTime; transform.Translate(0, 0, transAmount); To FixedUpdate , it now works perfectly , thank you both of you , I'm sure I'll use both methods in future.