I’m currently working on a bit of a racing game. I already have a nice track and car and driving works pretty good as well. However, I was wondering if some of you pros could help me out on the following issue:
The user is supposed to drive into one direction only. Therefore I want to avoid or at least notify the user, in case he makes a u-turn.
Can anyone suggest, how I’d go about implementing a routine, that can detect such a case?
The easiest way would be to check the velocity vector and see if it is going in the opposite direction of where it is supposed to be heading. If velocity is not available you could sample the position each frame and check the difference between two frames to see how far it moved in that time and in what direction. For example, if their velocity.z is negative, that could mean they are going the wrong way. That help?
If thats the case you may could check to see if they ever turn more than 90 degrees or so over a certain period of time. If they do that you may be able to tell they are doing a u-turn.
Another trick would be to create colliders behind the car as they progress down the track. The colliders would only stay in-tact a few meters back so that you wouldn’t be generating a ton of them. If the player ever collides with one, you know they are going backwards.
This post is too old, but another alternative is to create huge cubes with their forward vector pointing at the way the car should be moving (if you have a turn, just create a couple of short cubes with the forward aiming where the car should be going), and set their Box colliders to Triggers, and name them all the same. For example, WrongWayTriggers. And disable their renderer.
See “sample.jpg” attached. The white cubes are the triggers, the gray path is the track.
Then, on your Car script (or create a JS script and attach it to the Car where the rigidbody is), just add something like code:
function OnTriggerStay(other : Collider)
{
if (other.name == "WrongWayTriggers") {
// we're at the trigger!
// get the angle between us (the car) and the trigger
var angle : int = Vector3.Angle(other.transform.forward, transform.forward);
// if the angle is > 90 degrees, we're facing the wrong way!
if (angle >= 90) {
print("You're going the wrong way!");
} else {
print("You're going the right way!");
}
}
}
This code is pretty self explanatory and definitely needs tweaking on your hand.
For instance, it makes no sense to print every frame if the user is going either the right or the wrong way, so you should set a flag for that.
I’m not sure how heavy having box triggers is, but my guess is not that heavy at all.
Really nice and quick implementation nvarcha! Took me 2 mins to make it on my track! Thanks!
This does not cover a car going backwards. One idea that might be implemented is using a flag with a different collider on the car when driving back. Hope that helps too!