- Home /
How do I increase a speed variable over time?
I just need my car that follows way-points to go 0 to 30 in "x" amount of seconds after its ray shows a false hit. I'm trying to understand mathf functions but everything I try isn't working. Please help. Thanks!
using UnityEngine;
using System.Collections;
public class rayCast_car2 : MonoBehaviour
{
public GameObject car_1;
public float distanceToSee = 6f;
private bool targetHit;
private civic2MoveOnPath script;
void Start()
{
script = car_1.GetComponent<civic2MoveOnPath>();
}
void Update()
{
RaycastHit hit;
Ray slowDown = new Ray(transform.position, transform.forward * distanceToSee);
Debug.DrawRay(transform.position, transform.forward * distanceToSee, Color.magenta);
{
if (Physics.Raycast(slowDown, out hit, distanceToSee))
{
if (hit.collider.name == "Body Collider" && !targetHit)
{
Debug.Log("hit");
targetHit = true;
script.speed = 0f;
}
}
else if (targetHit)
{
Debug.Log("Not Hit");
targetHit = false;
script.speed = 30f;
}
}
}
}
Answer by Kossuranta · Jan 18, 2017 at 09:30 AM
Your question is little vague of what you actually need, but here is example code that would change speed over time until target is met.
using UnityEngine;
public class SpeedExample : MonoBehaviour
{
float currentSpeed = 0f;
float targetSpeed = 30f;
void Update ()
{
if (currentSpeed < targetSpeed)
currentSpeed += Time.deltaTime;
}
}
I am making a traffic simulation that have cars following waypoint paths. They detect each other with a raycast and stop behind each other. I just want to make the start up of each car more believable when they have to move again by making their acceleration smoother, and not having it jump immediately to 35 mph.
Next I have to figure out how to put this in a coroutine or something to delay the start up of each car as they move.
Thank you for the help!!