- Home /
How to add drift to top down car mechanics?
I'd like to add a sliding drift mechanic when spacebar is held. The code is for a 2d top down racing game. If there is already an answer for a question like this please direct me to it. Here is my pre-existing code:
using UnityEngine;
using System.Collections;
public class Car : MonoBehaviour {
public float power = 3;
public float maxspeed = 5;
public float turnpower = 2;
public float friction = 3;
public Vector2 curspeed ;
Rigidbody2D rigidbody2D;
// Use this for initialization
void Start () {
rigidbody2D = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
curspeed = new Vector2(rigidbody2D.velocity.x, rigidbody2D.velocity.y);
if (curspeed.magnitude > maxspeed)
{
curspeed = curspeed.normalized;
curspeed *= maxspeed;
}
if (Input.GetKey(KeyCode.W))
{
rigidbody2D.AddForce(transform.up * power);
rigidbody2D.drag = friction;
}
else if (Input.GetKey(KeyCode.S))
{
rigidbody2D.AddForce(-(transform.up) * (power/2));
rigidbody2D.drag = friction;
}
if (Input.GetKey(KeyCode.A))
{
transform.Rotate(Vector3.forward * -turnpower);
}
else if (Input.GetKey(KeyCode.D))
{
transform.Rotate(Vector3.forward * turnpower);
}
noGas();
}
void noGas()
{
bool gas;
if(Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.S))
{
gas = true;
}
else
{
gas = false;
}
if (!gas)
{
rigidbody2D.drag = friction * 2;
}
}
}
Comment
Your answer
Follow this Question
Related Questions
How to make top down car movement? 1 Answer
How to make car accelerate/decelerate over time 2 Answers
Car exhaust Flame in unity 1 Answer
Mario Kart Style Drifting 0 Answers