- Home /
add real time
Hi! I want to add real time in my game. When the game begins it begins and when the game over it finish.If time is bigger than 5 minutes player win 50 point , if time is less than 5 minutes and bigger than 3 minutes player win 100 point , if time is less than 3 minutes and bigger than 1 minutes player win 150 point. How can I do it ?
I think you need to provide more info about what you want. Below you have a full script but do you need since the game started or since the level has started?
Answer by Rati_Old · Aug 30, 2012 at 11:50 AM
You can get the time with "Time.time".
http://docs.unity3d.com/Documentation/ScriptReference/Time.html
Answer by Bunny83 · Aug 30, 2012 at 11:51 AM
Well, Unity provides Time.realtimeSinceStartup if you want to have real seconds. Usually you would use Time.time. However it is scaled with Time.timeScale, that comes in handy if you want to do a slowmotion effect or you want to pause the game. realtimeSinceStartup will never stop no matter what you do in game.
Regardless of the "time base" you want to use, you have to store the start time in a variable, so you can calculate the difference from the start point.
// UnityScript
var startTime = 0.0f;
var timeTaken = 0.0f;
// call this function when you want to start your game
function StartGame()
{
startTime = Time.time;
}
// This function will return the time in seconds that have passed since the start time
function GetCurrentGameTime() : float
{
return Time.time - startTime;
}
// call this function when the game is over. it will return the points depending on the timeTaken.
function StopGame() : int
{
timeTaken = GetCurrentGameTime();
if (timeTaken > 5*60)
return 50;
if (timeTaken > 3*60)
return 100;
if (timeTaken > 1*60)
return 150;
return 1000;
}
In most games it's better to calculate the points on a mathematical formula. This way the user get different points for every fraction of a second he saved.
function StopGame() : int
{
timeTaken = GetCurrentGameTime();
float t = Mathf.Clamp01(timeTaken / (5*60.0f));
t = 1.0f - t;
return 50.0f + t*500.0f;
}
This will always return 50 points plus a bonus depending on the time taken if you're under 5 min. The closer you come to 0 the higher the bonus will get. If the player completes the game in 0 seconds (just in theory) he will get a bonus of 500 points.
Here's are some samples:
timeTaken bonus total
300sec 0 50 // 5 min 0 sec
240sec 100 150 // 4 min 0 sec
239sec 101 151 // 3 min 59 sec
235sec 108 158 // 3 min 55 sec
70sec 383 433 // 1 min 10 sec
Your answer
Follow this Question
Related Questions
putting the date into a variable 1 Answer
Instantiating object after some fixed time... 2 Answers
Frame dependant game. Using update vs fixed update. 3 Answers
Time Based Shooter 0 Answers