I'm trying to make a 2D car driving game in Unity and I'm having problems with my code.
I am able to move forward,backward,turn left/right using arrow key from my present code
using UnityEngine;
using System.Collections;
public class CarControll : MonoBehaviour {
// Use this for initialization
float speedForce = 15f;
float torqueForce = -200f;
float driftFactorSticky = 0.9f;
float driftFactorSlippy = 1;
float maxStickyVelocity = 2.5f;
float minSlippyVelocity = 1.5f;
bool move=false;
public bool forwardArrow=false;
public bool backwardArrow=false;
public bool rightTurn=false;
// Use this for initialization
void Start () {
}
void Update() {
move=true;
}
// Update is called once per frame
void FixedUpdate () {
Rigidbody2D rb = GetComponent<Rigidbody2D>();
float driftFactor = driftFactorSticky;
if(RightVelocity().magnitude > maxStickyVelocity) {
driftFactor = driftFactorSlippy;
}
rb.velocity = ForwardVelocity() + RightVelocity()*driftFactor;
if( Input.GetButton("Accelerate") || Input.GetButtonDown("Forward") || Input.GetKeyDown(KeyCode.UpArrow)) {
Debug.Log ("Uparrow....................................................");
rb.AddForce( transform.up * 20);
}
if( forwardArrow==true) {
rb.AddForce(transform.up*0.5f);
}
if(backwardArrow==true) {
rb.AddForce( transform.up * -speedForce/25f );
}
if(Input.GetButton("Brakes") || Input.GetButton("Backword") || Input.GetKeyDown(KeyCode.DownArrow)) {
rb.AddForce( transform.up * -speedForce/2f );
}
float tf = Mathf.Lerp (0, torqueForce, rb.velocity.magnitude / 2);
rb.angularVelocity = Input.GetAxis ("Horizontal") * tf;
}
Vector2 ForwardVelocity() {
return transform.up * Vector2.Dot( GetComponent<Rigidbody2D>().velocity, transform.up );
}
Vector2 RightVelocity() {
return transform.right * Vector2.Dot( GetComponent<Rigidbody2D>().velocity, transform.right );
}
public void MoveForward() //forward button
{
forwardArrow = true;
backwardArrow = false;
}
public void MoveBackward() backward button
{
backwardArrow = true;
forwardArrow = false;
}
public void RightTurn() //right button
{
rightTurn = true;
}
}
I have added four button(Forward,backward,right,left).Now I need to move the car using this button. The car is moving Forward,backward using the button but when Press the right/left button the car is not Turing left/right while move.But its working perfectly on key press.Can anyboady help solving this issue