- Home /
Someone can help with Ray/Collide?
Hello people, im getting some issues with my script, i have a prefab called Car, i instantiate in some positions in the streets of the city, and we have semaphores, i have a script who can check every frame in Update() if the car have some collider in front he stop. But the car stop, and the other hits the car ahead, then the other stops, then the other hits, stop, hit, stop, hit, i dont know what is going on. I want only the cars to stop in every collider.
void Update(){
if(carSpeed){
transform.Translate(0,0,Time.deltaTime * -10);
}
if(collideDetect){
carSpeed = false;
}
else{ carSpeed = true; }
RaycastHit hit;
if (Physics.Raycast(transform.position, new Vector3(0,0,20), out hit))
{
if(hit.collider.gameObject.name.Contains("Semaphore Trigger") && (hit.distance < 2.5f) ||
hit.collider.gameObject.tag.Contains("Car") && (hit.distance < 2.5f))
{
collideDetect = true;
}
}
else { collideDetect = false; }
}
someone have an idea?
Set up something for synchronising it better. Try making the cars slow down gradually as they approach objects- the speed they move at should be proportionate to the distance to the nearest obstacle. That way, when you have cars travelling behind each other, you don't get the stop-start thing (except for a subtle speed change).
maybe a rigidbody.velocity will be a great helper here or you have any better idea?
You can easily retrieve the distance between two cars, using raycast and then hit.distance. Then you can apply a speed depending on that distance, simply
if(hit.distance
If you have a constant speed for the car, simply apply a stronger counterForce as it gets closer. So that
if (distance < 2m) counterforce = pushing force -> 0
Dosen't work with force or something like that, the cars continue sometimes to hit the others.
Answer by aldonaletto · May 05, 2012 at 04:12 PM
You're translating the object in its forward direction at -10 units/second (Translate assumes local space by default), but you're doing a raycast in the world forward direction - thus when the car isn't going in the world +Z direction the raycast fail miserably. You could use the car's forward direction instead:
if (Physics.Raycast(transform.position, transform.forward, out hit, 20)){
...
Another thing: you must specify the raycast range in the 4th parameter - the direction vector length doesn't make any difference.
NOTE: The car seems to be moved backwards (you're using velocity = -10). No matter why (and if) you're doing this, the ray must be cast in the direction the object is going - in other words, maybe you should use:
if (Physics.Raycast(transform.position, -transform.forward, out hit, 20)){
...
$$anonymous$$y bad! The answer was posted incomplete - now it's ok.
Thanks buddy this help me. But i make a simple small cube collider below the car to the line hit the collider. Thanks for your time (: