- Home /
How to add car speed to a car controller script
Hello
Im very new to unity and coding I have a car controller script and would like to able to change the speed the car goes does anyone know a script I can add
so at the moment my code allowd to move foward and back and tern left and right
[code=CSharp]using UnityEngine;
public class Car : MonoBehaviour { public float maxTorque = 5000000f;
public Transform centerofMass;
public WheelCollider[] wheelColliders = new WheelCollider[4];
public Transform[] tireMeshes = new Transform[4];
private Rigidbody m_rigidBody;
void Start()
{
m_rigidBody = GetComponent<Rigidbody>();
m_rigidBody.centerOfMass = centerofMass.localPosition;
}
void Update()
{
UpdateMeshesPositions();
}
void FixedUpdate()
{
float steer = Input.GetAxis ("Horizontal");
float accelrate = Input.GetAxis ("Vertical");
float finalAngle = steer * 45f;
wheelColliders [0].steerAngle = finalAngle;
wheelColliders [1].steerAngle = finalAngle;
for (int i = 0; i < 4; i++)
{
wheelColliders[i].motorTorque = accelrate * maxTorque;
}
}
void UpdateMeshesPositions()
{
for(int i = 0; i < 4; i++)
{
Quaternion quat;
Vector3 pos;
wheelColliders[i].GetWorldPose(out pos, out quat);
tireMeshes[i].position = pos;
tireMeshes[i].rotation = quat;
}
}
} [/code]
I have a problem with that is I have set it really high as you can see but the car still goes to slow
What if you change
wheelColliders[i].motorTorque = accelrate * maxTorque;
to
wheelColliders[i].motorTorque = accelrate * speed * maxTorque;
and add a public float speed
to the class and set it in editor. It could also be that this is not the part that its controlling the speed of the car though.
Answer by a161803398874 · Jul 29, 2017 at 08:18 AM
you multiply your variable "accelrate" by another variable you need to add to your script or change maxtorque
wheelColliders[i].motorTorque = accelrate * maxTorque *newVariable;
Your answer
Follow this Question
Related Questions
How make breaks and maximum speed 0 Answers
Question about the speed in the cartutorial 0 Answers
Can you help my with WheelColliders? 0 Answers
How to set speed limit of car? 3 Answers