everyone. I am new to Unity 2D and C# and I was wondering how I could stop my car from gliding and sliding forward in my game when I don't want it to since it doesn't really feel like I am in control of my car if it's slipping so much. I would like it so if I don't give the car any inputs, or give counter inputs that the car almost immediately stops or starts moving the other way. I have tried creating a Physics2D material and increasing the friction but it really had no effect on the gameplay. I've also tried checking so that if there is no player inputs the rb.velocity is set to 0, or around .2 of what it currently is so it's a smoother stop but that only works if the player moves then lets go of the movement key, not if they try moving the opposite direction. I've also thought about checking which direction the car is moving by comparing a previous location with a current one then adding force in the opposite direction to stop the car but that seems very performance-intensive and I don't really know where I would start. If anyone has any suggestions for how I would go about doing this then please let me know how. This is the code I have so far:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CarController : MonoBehaviour
{
public Rigidbody2D carRigidbody;
public Rigidbody2D backTire;
public Rigidbody2D frontTire;
private float movement;
public float fspeed = 100;
public float bspeed = 60;
public float carTorque = 10;
public float decVel = .9f;
private bool beganMoving;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
movement = Input.GetAxis("Horizontal");
}
void FixedUpdate() {
if (movement == 1 || movement == -1) {
beganMoving = true;
}
if (movement == 0 && beganMoving) {
backTire.velocity = new Vector2 (backTire.velocity.x * decVel * Time.fixedDeltaTime, backTire.velocity.y);
frontTire.velocity = new Vector2 (backTire.velocity.x * decVel * Time.fixedDeltaTime, backTire.velocity.y);
}
backTire.AddTorque(-movement * bspeed * Time.fixedDeltaTime);
frontTire.AddTorque(-movement * fspeed * Time.fixedDeltaTime);
carRigidbody.AddTorque(-movement * carTorque * Time.fixedDeltaTime);
}
}