I am working on a 2D driving game.I have a button(forward).I need to move the vehicle by pressing on the button. When the button is pressed the vehicle should accelerate upto its maximum speed and when the button is release the vehicle should gradually slow down.
float rotateSpeed=0.1f;
float speedForce = 15f;
float torqueForce = -200f;
float driftFactorSticky = 0.9f;
float driftFactorSlippy = 1;
float maxStickyVelocity = 2.5f;
float minSlippyVelocity = 1.5f;
bool moveForward=false;
bool moveBackward=false;
bool turnLeft=false;
bool turnRight=false;
Vector3 myRot;
void FixedUpdate () {
Rigidbody2D rb = GetComponent<Rigidbody2D>();
float driftFactor = driftFactorSticky;
if(RightVelocity().magnitude > maxStickyVelocity) {
driftFactor = driftFactorSlippy;
}
rb.velocity = ForwardVelocity() + RightVelocity()*driftFactor;
//Move rover forward and backward
if(Input.GetKey(KeyCode.UpArrow) || moveForward==true || Input.GetButton("Accelerate") ) {
Debug.Log ("Uparrow....................................................");
rb.AddForce( transform.up * 0.3f);
}
if(Input.GetKey(KeyCode.DownArrow) || moveBackward==true || Input.GetButton("Brakes") ) {
Debug.Log ("break....................................................");
rb.AddForce( transform.up * -speedForce/30f );
}
float tf = Mathf.Lerp (0, torqueForce, rb.velocity.magnitude / 2);
rb.angularVelocity = Input.GetAxis ("Horizontal") * tf;
if (Input.GetKey (KeyCode.RightArrow) || turnRight==true) {
transform.Rotate(0,0,-0.5f);
}
if (Input.GetKey (KeyCode.LeftArrow) || turnLeft==true) {
transform.Rotate(0,0,0.5f);
}
}
Vector2 ForwardVelocity() {
return transform.up * Vector2.Dot( GetComponent<Rigidbody2D>().velocity, transform.up );
}
Vector2 RightVelocity() {
return transform.right * Vector2.Dot( GetComponent<Rigidbody2D>().velocity, transform.right );
}
this is working fine but the problem is that when I release the forward button the speed of vehicle is not getting slow down.
Can anybody help me please