- Home /
Question by
MohammadAlizadeh · Sep 15, 2015 at 11:40 AM ·
speedcar-tutorial
Car Speed Limit (unity5)
Hi
i want a speed limitation For my car script
Thank you!
using UnityEngine;
using System.Collections;
public class Car : MonoBehaviour
{
public float topSpeed = 100;
private float currentSpeed = 0;
private float pitch = 0;
public float maxTorque = 50f;
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()
{
currentSpeed = transform.GetComponent <Rigidbody> ().velocity.magnitude * 2.6f;
pitch = currentSpeed / topSpeed;
transform.GetComponent <AudioSource> ().pitch = pitch;
UpdateMeshesPositions();
}
void FixedUpdate()
{
float steer = Input.GetAxis("Horizontal");
float accelerate = 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 = accelerate * 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;
}
}
}
Comment
Answer by NiteshRathi05 · Apr 05, 2018 at 10:08 AM
Try this code, maybe this will work for you.
float speed = GetComponent ().velocity.magnitude 2.6f; If (speed < 100) { for(int i = 0; i < 4; i++) { wheelColliders[i].motorTorque = accelerate maxTorque; } } else { for(int i = 0; i < 4; i++) { wheelColliders[i].motorTorque = 0; } }
Your answer
![](https://koobas.hobune.stream/wayback/20220612033828im_/https://answers.unity.com/themes/thub/images/avi.jpg)