- Home /
How can I make a "Fastest Lap" scoring system for a racing game?
I am making a racing game and need a scoring system. I want it to count the time that it took to do a lap and that you get more points if you do the lap faster (the faster you finish the lap the more points you get). So how do I script or make it?
Answer by Jesus_Freak · Nov 22, 2010 at 01:19 AM
all right! make a cube, turn it into a trigger (check "isTrigger") and tag it "FinalLap" you'll add this script to your car or whatever you'r racing. and turn off the mesh renderer.
var points = 0;
function OnTriggerEnter(hit : Collider) { if(hit.gameObject.tag == "FinalLap") { Finish(); } }
function Update() { print("I finished in: " +points); } function Finish() { if(Time.time <= 90) //if you make it before 90 seconds { points += 5; //add points } if(Time.time <= 50) //if you made it before 50 seconds { points += 10; //add points } }
that should add points based on the time it took to hit the trigger (box) and prints in the Debug.Log that you finished in a predefined time.
hope this helps!!!
Answer by duck · Nov 22, 2010 at 01:54 PM
The way I implement this is to have a series of waypoint positions around the track which are collected together as an array of Vector3s. (See here for more detail on that)
I then track each waypoint that the user passes using a simple "Dot" vector function. Because I know how many waypoints there are, I can track when the user has passed the last one, and begin checking for the first waypoint again. Whenever the first waypoint is passed, I update the lap counter, and record the lapTime.
This method also gives you easy access to how far around the track a user is (eg, if they've passed 45 of 150 waypoints, they have completed ((45/150)*100)% of the lap!
int lapNum = 1; int waypointNum = 0; Vector3[] waypoints; // this should be filled with vector3 world positions as show in answer linked above in this question
void Update() { // we get the current target waypoint and the next waypoint // (in order to calculate the waypoint's direction) waypoint = waypoints[waypointNum]; nextwaypoint = waypoints[ (waypointNum+1) % waypoints.Length ];
// route direction at target waypoint:
waypointDirection = nextwaypoint - waypoint;
// delta from car to target waypoint
Vector3 waypointDelta = wayPoint-transform.position;
// check whether car has passed target waypoint, using Dot Product
if (Vector3.Dot( wayPointDirection, waypointDelta ) < 0)
{
// if so, step to the next waypoint number.
waypointNum++;
// check whether we passed the last one
if (waypointNum == waypoints.Length)
{
// we completed a lap. record time and reset waypoint tracking to zero.
lapTime = (Time.time - lapStartTime);
if (lapTime < fastestLapTime) {
// new fastest lap!
}
waypointNum = 0;
++lapNum;
lapStartTime = Time.time;
}
}
}