How to end a game after an interval of time(in XNA) - xna-4.0

I have created a game using XNA Game Studio. It consists of a square randomly moving anywhere and on clicking it, the score increases by one.
Now, what I want to do is, I want to end it after a time interval of, say, 100 seconds. So how do I do it? And where should I write that part of the code? That is, in which method? I am very new to XNA. Its just two days since I have started learning it.

In your update loop check the elapsed game time greater than 100 seconds:
int counter = 0;
protected override void Update(GameTime gameTime)
{
counter += gameTime.ElapsedGameTime.TotalSeconds;
if ( counter > 100 )
{
//end the game...
}
}
If you want the total game time since the game started, you can use the TotalGameTime property instead, then you won't need the counter.

Related

Unity - Score stays on 1

Looking around in the forum. Finally, I decided to join in this big community for the support it provides!
I am creating this post because I am struggling in a 2D game that I am creating in Unity.
The game keeps scoring the number one once the play button is clicked. It increases the score once the food is collected, but the problem here is that once I click on "Play" button the score is already on "1" instead of "0".
Code in the following statement:
Scoring System
Collect C#
Thank you for your help!
You could do 2 things:
Add a Start() function in Scoring System script.
private void Start(){
// This would make sure that score is 0 from the first frame
scoreText.GetComponent<Text>().text = " " + 0;
}
2)Instead of directly running the code on trigger use tags, assign the tag of Player to your player gameObject, then add this code.
void OnTriggerEnter2D(Collider2D collision)
{
if(collision.tag == "Player"){
ScoringSystem.theScore += 1;
// Destroy(collision.gameObject);
}
}

Timer Efficiency

I'm working on an AS3 project and for one of the effects I use timers to switch the colors then stop. The function is below.
//global variable
private var valueAnimationTimer:Timer = new Timer(50);
//constructor
valueAnimationTimer.addEventListener(TimerEvent.TIMER, scrollUp );
//function
private function scrollUp(e:TimerEvent):void
{
var i:int = e.currentTarget.currentCount as int;
if (i < 10)
{
if (colored){
if (i % 2 == 0){
ChangeColor(ico, flickerColor);
}
else{
ico.transform.colorTransform = new ColorTransform();
}
}
tfValue.y -= 7.5;
}
else
{
RemoveFilters(ico);
tfValue.y = ico.height / 2;
e.currentTarget.reset();
RemoveSprite(tfValue);
colored = false;
}
}
Each character (object) has it's own version of this function and it happens at different times (like when it is injured or poisoned). The listener is added once in the constructor, it is only removed when the character dies and is removed from the stage. The issue here is after the timer is used on at least 3 characters, the frame rate begins to drop. Every time the function is called, the frame rate drops lower and lower.
What I don't understand is, if the timer is stopped, and the listeners are only added once so it doesn't overload the stack, then why does the frame rate begin to decline after the listener is actually used? It doesn't run forever only for a small amount of time, but it happens again and again. When the frame rate drops the entire program begins to lag badly and eventually freezes. I have no idea what is causing this
Also be aware that inside of the Timer function, the first number is your count in MILLISECONDS and the second is repeat count
var fl_TimerInstance:Timer = new Timer(240000, 1);
So this example above is a 4 minute timer that repeats 1 time
I bring this up because yours is set for 50 milliseconds which is very quick lol

XNA game : calculate time between two shoots

I'm trying to make a game with the XNA library. I want a sprite to throw a fireball to hit falling asteroids. But I have a problem with pressing the concrete key: I want to throw fireballs, for example, with one second between throws.
I want to measure the time difference between creating instances. How can I do that?
UYou can use the ElapsedGameTime property of the gameTime variable passed to the Update method like this:
const float shootTimer = 1.0f;
float elapsedTime = 0f;
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
elapsedTime += gameTime.ElapsedGameTime.TotalSeconds;
if(elapsedTime >= shootTimer && /* Your logic to see if you should shoot a fireball */ )
{
// Shoot the fireball!
elapsedTime = 0f;
}
base.Update(gameTime);
}
Basically, what you are doing in the above code is setting a minimum value (seconds) that need to pass between each shot.
Then you create a variable that will store the amount of time that has passed between each shot.
In the Update method, you add the time between each Update call and then check if it is bigger than the timer, and if it is, then you shoot and reset the elapsed time.
Note: I wrote that piece of code out of the top of my mind so it may have some minor issue.
Each call to Update of your main Game class or any GameComponent receives an instance of GameTime as an argument. Its property ElapsedGameTime can be used to accumulate the passage of time.

Swift: Repeat action after a random period of time

Previously, with Objective-C I could use performSelector: in order to repeat an action after a random period of time which could vary between 1-3 seconds. But since I'm not able to use performSelector: in Swift, I've tried using "NSTimer.scheduledTimerWithTimeInterval". And it works in order to repeat the action. But there is a problem. On set the time variable to call a function that will generate a random number. But it seems that NSTimer uses the same number every time it repeats the action.
What that means is that the action is not performed randomly, but instead, after a set period of time that is generated randomly at the beginning of the game and it is used during all the game.
The question is: Is there any way to set the NSTimer to create a random number every time it executes the action? Or should I use a different method? Thanks!
#LearnCocos2D is right... use SKActions or the update method in your scene. Here is a basic example of using update to repeat an action after a random period of time.
class YourScene:SKScene {
// Time of last update(currentTime:) call
var lastUpdateTime = NSTimeInterval(0)
// Seconds elapsed since last action
var timeSinceLastAction = NSTimeInterval(0)
// Seconds before performing next action. Choose a default value
var timeUntilNextAction = NSTimeInterval(4)
override func update(currentTime: NSTimeInterval) {
let delta = currentTime - lastUpdateTime
lastUpdateTime = currentTime
timeSinceLastAction += delta
if timeSinceLastAction >= timeUntilNextAction {
// perform your action
// reset
timeSinceLastAction = NSTimeInterval(0)
// Randomize seconds until next action
timeUntilNextAction = CDouble(arc4random_uniform(6))
}
}
}
use let wait = SKAction.waitForDuration(sec, withRange: dur) in your code. SKAction.waitForDuration with withRange parameter will compute random time interval with average time = sec and possible range = dur
Generate a random time yourself and use dispatch_after to do the action.
For more information on dispatch_after, see here. Basically you can use this instead of performSelector

Timeline animation in JavaFX

I've been trying to add an animation to my bubble chart in my UI but have ran into some issues. I'm trying to increase the size of the bubble at different stages to show a gradual change but its just drawing it at its full size instead of at every stage.
Here's the timeline code
tl.getKeyFrames().add(
new KeyFrame(Duration.seconds(30),
new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent actionEvent) {
//for (XYChart.Series<Number, Number> series : liveDemoBubbleChart.getData()) {
for(int i = 10; i>0; i--) {
series1.getData().add(new XYChart.Data(5,5, ProjectProperties.getInstance().getSportsTweetsCount()/i));
}
The sport tweet count is the final value for the bubble and I'm dividing it by different amounts to show the build up to the final value.
Does anyone have any ideas as to why this isn't working as I expect?
The KeyFrame taking a Duration and an EventHandler<ActionEvent> simply executes the EventHandler's handle(...) method after the time specified by the Duration. So your code causes the entire for loop to be executed after a pause of 30 seconds.
You probably want to supply a KeyValue instead, providing a property to be set and the target value after 30 seconds. The value will then be interpolated at times in between. Have a look at the tutorial to see if it helps.

Resources