I can't find any answers to this. What I want is to set a 5 min time limit that begins when the level begins and ends when level ends. I also want it to kill the player if it runs out. This is for Unity2D and I want the timer to be seen at top left or right of screen. So basically I need a time limit like that of Super Mario. In C# code please.
Break up your problem into easier tasks. You will need some type of timer, and you will want to know how to 'kill' the player.
To create a timer, you can take advantage of how Update runs once per frame. Unity also comes with a Time class. In Time, there is a variable deltaTime which keeps track of the time in seconds to complete the last frame. Some other things you might want to add on to your class that acts as a timer is when to start and stop the timer.
To output the value from a timer to the game, you might want to use Unity's UI system and canvas. You might create a text object that is part of a canvas and anchor that text object to the top left corner.
To 'kill' a player, you can have some method that runs once the timer reaches the time in question and run the kill logic you want.
Helpful links:
MonoBehavior Update: https://docs.unity3d.com/ScriptReference/MonoBehaviour.Update.html
Time: https://docs.unity3d.com/ScriptReference/Time.html
UI: https://unity3d.com/learn/tutorials/topics/user-interface-ui
You can create a class that keeps track of the timer and to check if the requirements to fail are still there.
In this case you can have a float for the timer, and a bool for the condition whenever you completed the level or not.
It the timer reaches zero, check if the bool is still false, if it is, then you call something like KillPlayer(). If you complete the level by hitting a trigger or anything that will know if the level should be considered finished, you set the bool to true.
So your final check could look like this:
public float levelTimer = 300f;
public bool levelComplete = false;
void Start()
{
levelTimer = 300f;
levelComplete = false;
}
void Update()
{
levelTimer -= Time.deltaTime;
if(levelTimer <= 0 && !levelComplete)
{
KillPlayer();
//Something like a Game Over screen maybe
}
}
I hope this help you in the right direction.
Related
So basically I have two questions. I am also copying off this video from 2014: https://www.youtube.com/watch?v=w8JgpEjm8i8&t=2792s
Question 1
At the end of the video above the guys computer completely crashed and he wasnt able to show the end of how to setup a death animation for my player (link). So currently I have setup a movie clip of the death animation - just the playing spinning around - and put it in another movie clip called 'All Sprites' in which I have my other movie clips such as the different walking directions. So I have placed it in there, labelled it with "Link Death Frame". I then went back to the main script and added code so that once my player dies, the animation will play. Such as:
~
if(linkHealthBarMC.scaleX <= 0.01)
{
linkAlive = false;
}
trace(linkAlive);
if(linkAlive == false)
{
linkMC.gotoAndStop("Link Death Frame");
}
~
However, the issue comes in which the animation doesnt actually play, it just goes straight to the first frame and doesnt play. I have tested it and I know for sure that it gets stuck on the first frame and that something must be wrong with the animation as I tested it with another animation and it worked fine (once I met the requirements for the animation to play). So does anyone have any idea how I can fix this issue so that my character can play a death animation?
Question 2
How do I stop time? Like just completely freeze everything after my character is dead? Because at the moment I am just going to the first frame of the death animation and can still move and attack.
I'd assume this is on an EnterFrame loop. Then you would have two possible causes for this:
1.) You're loop is constantly checking if the 'linkAlive' if statement is false (which it is) and setting your Animation to the first frame. You can check this method by putting a Trace statement in your if statement and if the output window overflows, then that's your culprit.
2.) What you want is gotoAndPlay(-insert label here-)
Tho it is outside the scope of the question you have, I create a variable~Switch State machine to control states for me:
1.) Current State as a number (int, number, or uint)
2.) function with a switch statement (Switch is kind of a fancy if Statement)
3.) inside the cases are instructions
switch(current_state){
case 1:
linkMC.gotoAndPlay('death animation');
break;
}
if (current_state != 1){
-put movement code here-
}
This is close to what I use for my game. Just checking states or you can have a variable like the one above that explicitly checks for the death state and remove the ability to move. If you use a mouse (and I assume event listener) then you can remove the event listener for the mouse. If you use a solution like keyboard inputs then an if statement would be more what you are looking for.
I'm developing my first game and I have a player class (FlxSprite) that has a death animation.
I want to remove the player from the stage as soon as the animation ends, but if I use:
player.animation.play('death');
remove(player);
The animation doesn't finish and the player just disappears.
The way I handle this in most of my projects is something like this:
override public function update(elapsed:Float):Void
{
if (!alive)
{
if (animation.finished)
{
exists = false;
}
super.update(elapsed);
}
// other update stuff...
super.update(elapsed);
}
override public function kill():Void
{
if (!alive || !exists)
{
return;
}
alive = false;
animation.play("death", true);
// Note: I DO NOT call super.kill() because I want to leave exists = true
}
And, in your PlayState or wherever you want to remove the object, just check if (!player.exists) remove(player);, I guess? I don't usually use remove, I just wait until the state is destroyed and then clean everything up with FlxDestroyUtil.
Your question isn't super clear, but I'll try help anyway.
Because of the way the game loop is looping, the remove function kills off the sprite before the animation plays. You can check to see when the animation is finished by putting an if statment in your update function, like so.
if (animation.finished) kill()
If you need an actual timed delay, you can see my previous answer where you increase a variable by FlxG.elapsed every update on a variable until it exceeds your timer length.
I hope this answers your question. You may want too look at methods such as kill() in the HaxeFlixel docs, as I think you might be confused with remove().
EDIT: very sorry, forgot to include one important detail. It is likely that you are calling animation.play every single frame - stop once your death animation plays. In my code I saw I have an isDying variable that stops any new animations starting, and checks to see if the current animation is finished. Without this, the finished variable might not flip.
I implemented another version of this project with Java Swing, but because it could not support multi-touch functionality, I am rewriting it using JavaFX.
So I want the program to wait either for a user clicks a Button object or for a timeout, say 5 seconds - this means that the program would present a Button on the screen at one point and does not proceed to the next phase until either the Button is pressed or 5 seconds pass without it being pressed.
Clearly, detecting a click is elementary because adding ActionEvent would solve it. The tricky part is measuring the time. When implementing with Swing objects, I would have a while loop and have Thread.sleep(very_short_time_interval) inside to periodically check the elapsed time:
lastUpdate = System.currentTimeMillis();
while ((!pressed) && (System.currentTimeMillis() - lastUpdate <= timeout)) {
Thread.sleep(50);
}
The purpose of the Thread.sleep() in the pseudo-code above was to prevent the while loop from executing too often. Though it does not seem like the best practice, this trick apparently worked when used with Swing objects. But I realized after trying out the same thing with JavaFX Button objects, it turns the shape of the mouse pointer to a circulating ring, indicating the process is busy on Windows. What is worse is the button would not recognize mouse inputs during this busy phase. I am guessing JavaFX objects are heavier than Swing objects and is causing this problem as a result.
So my question is, would there be another way, possibly native function in JavaFX to make a Button expire without requiring a while loop? Or would there be some lighter weight objects than Button that works in a similar manner (listening to mouse clicks) that could work with the original while approach?
You can use a PauseTransition to wait for n-seconds. On its setOnFinished you can add an action to be performed. If the button has been pressed, you can cancel the transition on its action.
final PauseTransition pt = new PauseTransition(Duration.millis(5000));
pt.setOnFinished( ( ActionEvent event ) -> {
doSomething();
});
button.setOnAction( (ActionEvent event) -> {
doSomething();
pt.stop(); // If the button has been pressed, stop the Transition
});
pt.play();
I have a timer set on my application using html 5 and jquery. Now when I move on to different tab or I minimize my window, the timer for that few seconds stops. I do not want this. And again as I open the window(tab or browser page, whatever u say)the timer starts. But it gets pause for those seconds. What should be the issue ? What code should I write for it ?
I want that even though I minimize my window or look at new tab, my timer should be on.
Code for getting the timer is:
Here the timer is set and it runs, but as soon as i move my focus to other page, the timer is paused. A function is just shown here.
function showTime()
{
if(ms>=100){
ms = 0;
s++;
}
// calculates seconds and hours also
var temp= $("#clock").text(checkTime(h)+":"+checkTime(m)+":"+checkTime(s)+"."+checkTime(ms));
if(windows_focus=true){
timer=setTimeout('showTime()', 10);}
else if(windows_focus=false){
timer=setTimeout('showTime()', 100);
}
}
checktime is a function which just add a zero in front of numbers<10.
I just added in windows_focus=false also, as I thought if I move away, then also it should work, but i am not getting.
I tried using setInterval also, when I use setInterval, then even though I minimize the window the timer is getting started. But the problem is that the time runs in a really weird manner. Runs very very fast.
Can anyone please help me out.
http://jsfiddle.net/JWxS6/44/ this might be useful to see my code.
I am really new, please help me out
This is a very strange problem, and all the people I had asked to confirm it said that it takes place.
I have a Threading.Timer instance which fires every 15 minutes. And if I call the PhotoChooser view and then select a photo from it, when going back to the calling page my application calls that timer's callback! I tried different timers either it be Timer from Threading namespace or Dispatcher timer.
The same happens when being in my app I hold the back button of my device and then choose the app from the list.
My application is as plain as it can be - the timer with a callback and method calling PhotoChooser. Could anyone help with solution or workaround please?
Update:
My code construction is as follows:
private Timer _timer;
public void CallTimer()
{
var period = 15 * 1000 * 60;
_timer = new Timer(repeatTimer_Tick, null, 0, period);
}
private void repeatTimer_Tick(object state)
{
// Some action here
}
private void Stop()
{
if (_timer != null)
_timer.Dispose();
}
private void CallPhotoChooser()
{
// Some basic actions calling photochooser task
}
As explained in Windows Phone 7 Tombstoning the application is most likely tombstoned when the user presses and holds the back button or a launcher, like the PhotoChooserTask, is called. This happens unless the page is returned to in a matter of seconds.
You need to store the timer timeout in your application state somehow, or set the initial timeout to 15 minutes so it doesn't fire immediately. To store the application state, take a look at the article linked, it recommends doing this in the NavigatedFrom event which you can overload in the page code behind.
The time left before the timer fires is a bit more difficult. I guess to know how long it's left of a timeout you need to get the time with DateTime.UtcNow (which you can store in the application state) when creating the timer and calculate the next time it will fire upon resuming the application.
You should not be creating those long running timers :) Just handle the activation/deactivation and reset your timers, then reinstate them when photo chooser returns you back to your app.