The question is answered, right answer was accepted
Adding Acceleration to Simple Car Controller
I am currently working on a simple arcade style car game. I looked up a tutorial for a simple controller without the use of wheel colliders. It has a Top Speed variable, but no Acceleration, and I don't know how to implement it. Here is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class CarDrive : MonoBehaviour
{
private Rigidbody rb;
public float topSpeed;
// public float acceleration;
public float turnSpeed;
private float currentSpeed;
public float gravity;
public GameObject lights;
public Text speedText;
public bool lightToggle;
private bool isPressed;
private bool IsPressed
{
get { return isPressed; }
set
{
if(value == isPressed)
{
return;
}
isPressed = value;
if(isPressed)
{
lightToggle = !lightToggle;
lights.SetActive(lightToggle);
}
}
}
public float Speed
{
get
{
return currentSpeed;
}
}
void Start()
{
rb = GetComponent<Rigidbody>();
}
private void Update()
{
IsPressed = Input.GetKey(KeyCode.L);
var mph = currentSpeed * 2.237f;
speedText.text = mph.ToString("F0");
}
void FixedUpdate()
{
currentSpeed = rb.velocity.magnitude;
if (Input.GetKey(KeyCode.UpArrow))
{
rb.AddRelativeForce(new Vector3(Vector3.forward.x, 0, Vector3.forward.z) * topSpeed);
}
else if (Input.GetKey(KeyCode.DownArrow))
{
rb.AddRelativeForce(new Vector3(Vector3.forward.x, 0, Vector3.forward.z) * -topSpeed * 0.25f);
}
Vector3 localVelocity = transform.InverseTransformDirection(rb.velocity);
localVelocity.x = 0;
rb.velocity = transform.TransformDirection(localVelocity);
if(rb.velocity.magnitude > topSpeed)
{
rb.velocity = rb.velocity.normalized * topSpeed;
}
if(Input.GetKey(KeyCode.RightArrow))
{
rb.AddTorque(Vector3.up * turnSpeed * 10);
}
else if (Input.GetKey(KeyCode.LeftArrow))
{
rb.AddTorque(-Vector3.up * turnSpeed * 10);
}
rb.AddForce(Vector3.down * gravity * 10);
}
}
I'm sure it's an easy implementation, but I'm just not sure where it could go.
Answer by GTvsForza · Mar 09, 2021 at 03:19 PM
I figured it out (kind of). When I divided topSpeed by the Rigidbody's mass, it makes it accelerate slower than usual. I guess I could also multiply it by an acceleration factor to make it more realistic, but it's an arcade game, so not super worried about it right now. So, if someone could close this question, that would be great.
Follow this Question
Related Questions
I need help making a ball accelerate 0 Answers
CREATE Car collision Explosion unity 2d ? 0 Answers
How to set reverse speed limit of car? 0 Answers
How to re-enable multiple components in one script 0 Answers