Decrement Integer Spritekit - ios

I have a project in Sprite Kit and I am trying to make it so that a timer gradually decreases. For example if the timer float variable is set at 3.0, this would gradually decrease and be at 0, 3 seconds later. With the way that updates work in sprite kit its a horrible mess trying to get an integer to gradually decrease.
For example:
time+=1;
If I was to put this in an update void, it would increment extremely quickly and differently depending on frames and so forth. Is there a way I can Increment or Decrement a value at a steady rate no despite the fps in Sprite Kit?

You'd be better off getting the current time with each update and comparing it to some initial time to determine when 3 seconds pass.
Declare an ivar in your SKScene subclass:
#implementation MyScene {
NSDate* _timestamp;
}
When your timer starts:
_timestamp = [NSDate timeIntervalSinceReferenceDate];
Check your timer in your update pass:
- (void)update:(NSTimeInterval)currentTime {
if(_timestamp != nil && currentTime - _timestamp.timeIntervalSinceReferenceDate >= 3.0) {
// Perform your timer event
}
// Other updates
}

Related

Simple combo multiplier in sprite-kit

I am making a reaction game, where you can destroy enemys and earn points. Now I would like to have combo points if you destroy them fast and if there is a specific time gap the combo multiplier should go to zero again.
I would like to multiple the points like this: 2 * 2 = 4 * 2 = 8 * 2 = 16 * 2...
(you get 2 points if you destroy an enemy).
I add the points here:
if (CGRectIntersectsRect(enemy.frame, player.frame)) {
points = points + 1;
[enemy removeFromParent];
}
I could always multiply the current points with 2, but I want to reset the combo multiplier if there is specific amount of time without getting points.
I hope someone can help me.
(code in objective c please)
It seems no more complicated than recording the time the last enemy was destroyed and then in the update: method deciding if the combo has elapsed as no more enemies were hit in whatever timeout period you allow.
I am not familiar with Sprite kit, but the update appears to pass the current time; excellent. You will need to record the following:
timeout (time): The current timeout. This will reduce as the game progresses, making it harder.
lastEnemyKillTime (time): the time the last enemy was killed.
comboPoints (integer): How many points the user gets per hit. This will increase as the combo extends.
points (integer): The current score.
So, something like this:
#interface MyClass ()
{
NSTimeInterval _timeout;
NSTimeInterval _lastEnemyKillTime;
BOOL _comboFactor;
NSUInteger _points;
}
#end
I guess Sprite Kit uses an init: method; use it to initialize the variables:
- (id)init
{
self = [super init];
if (self != nil) {
_timeout = 1.0;
_lastEnemyKillTime = 0.0;
_points = 0;
_comboPoints = 1;
}
}
The update: method would be something like:
- (void)update:(NSTimeInterval)currentTime
{
BOOL withinTimeout = currentTime - _lastEnemyKillTime <= _timeout;
if (CGRectIntersectsRect(enemy.frame, player.frame)) {
_inCombo = withinTimeout;
if (_inCombo)
_comboPoints *= 2;
_points += _comboPoint;
_lastEnemyKillTime = currentTime;
[enemy removeFromParent];
} else if (_comboPoints > 1 && !withinTimeout) {
_lastEnemyKillTime = 0.0;
_comboPoints = 1;
}
}
You need to keep track on the last enemy casual timestamp and the factor. When the next kill is processed, you check the timestamp, if it is below threshold, you raise the factor. The time of the current kill replaces the timestamp.
You could create a FightRecorder class as singleton, if you don't have a better place yet (services or sth).
NSDate *newKillTime = new NSDate;
FightRecorder recorder = [FightRecorder instance];
if([newKillTime timeIntervalSinceDate:recorder.lastKillTime] < SCORE_BOUNDS_IN_SEC) {
recorder.factor++; // could also be a method
points = points + [recorder calculateScore]; // do your score math here
}
else {
[recorder reset]; // set the inner state of the fight recorder to no-bonus
}
recorder.lastKillTime = newKillTime; // record the date for the next kill

iOS Swift SpriteKit - how to detect time elapsed between user touches on sprites

I have set up a match-3 game, and I want to track the number of seconds a user takes to touch valid points (game piece sprites) on the game board:
(1) when a game level is loaded, if the user does not touch a sprite within 5 seconds, track this;
(2) while playing the game, if the time elapsed between the user touching a sprite is greater than 5 seconds, track this.
(I will use these results to provide a hint to the user).
I would like to use a NSTimer/NSTimeInterval for this, but not sure how to implement it.
I wouldn't suggest adding an integer as others suggested.
All you need is delta time. I'm assuming you have that part worked out, but I'll post it just in case
scene properties
// time values
var delta:NSTimeInterval = NSTimeInterval(0)
var last_update_time:NSTimeInterval = NSTimeInterval(0)
your scene's update method (also create an update method for your sprites, and pass delta into it here)
func update(currentTime: NSTimeInterval) {
if self.last_update_time == 0.0 {
self.delta = 0
} else {
self.delta = currentTime - self.last_update_time
}
self.yourSprite.update(self.delta)
your sprite's time properties
var timeSinceTouched = NSTimeInterval(0)
let timeLimit = NSTimeInterval(5.0)
your sprites update / touched method
func touched(){
self.timeSinceTouched = 0.0
}
func update(delta: CFTimeInterval) {
if self.timeSinceTouched < self.timeLimit {
self.timeSinceTouched += delta
} else {
// five seconds has elapsed
}

Alternative to `CACurrentMediaTime()` for scheduling events in SpriteKit

I'm relatively new to SpriteKit and am wondering what alternatives there are to using the CACurrentMediaTime() for scheduling events. For example, I may implement an algorithm that prevents a player from firing too many times by adding the last time they fired with some 'cool down' period, comparing it to the current media time:
BOOL canFire = self.lastFireInterval + self.coolPeriod < CACurrentMediaTime();
The problem I have run into is that if I decide to alter the speed of a node, or even the entire scene, this logic falls apart. For example, if I gave the player a speed-up power up, I could slow down all other nodes except for the player, but the timings would be messed up for enemies firing.
What other alternatives are there for CACurrentMediaTime() that factor in the speed of the node?
2 options come to mind regarding the timed to fire:
1) Create an ivar/property BOOL readyNextMove; for your player class. Then when your player shoots set the readyNextMove to false and add this code:
SKAction *wait = [SKAction waitForDuration:2.0];
SKAction *block0 = [SKAction runBlock:^{
readyNextMove = true;
}];
[self runAction:[SKAction sequence:#[wait, block0]]];
2) You can use the update:(CFTimeInterval)currentTime method to see how much time has elapsed from, for example you player shooting, and set readyNextMove accordingly.
It's a matter of taste. But for all games I keep an internal frame based clock which handles everything. I firmly believe this is the best way, but of course it depends on the scope of your project. This method is very rigid and guarantees continuity. If you use timers and your game lags, your continuity is thrown off (in some cases a shooter might shoot more times per frame than other parts of your game gets to move).
In aScene.h
long _currentTime = 0;
In aScene.m
-(void) update {
_currentTime++;
for(shooter * aShooter in self.shooters) {
[aShooter updateWithTime:_currentTime];
}
}
In your shooter.m
-(BOOL) tryShoot:(long)globalTime {
if(_lastShootingTime<globalTime-shootingCooldown) {
_lastShootingTime = globalTime;
[self fireBullet];
return YES;
}
return NO;
}
-(void) updateWithTime:(long)globalTime {
//...perform shooters action for that time frame
_lastUpdatedTime = globalTime;
}

Set A bool to true for two seconds then change back to false

As the question states, in spritekit I am trying to find a way to change my value of a bool from false, too true for x amount of seconds then change it back to false.
the logic is i have this var, isStunned, when my player comes in contact with x sprite i call it and my joystick is disabled since the player is "stunned"
if (controlButtonDown) { // If i pressed joystick
if (!isStunned) { // IF i am not stunned
//move player
When my player touches the glue, i set isStunned to yes and the joystick is disabled, however I am wondering of a way to only disable my joystick or not move my sprite for x amount of seconds. I know of SKAction and the wait sequence, but those are actions and I dont think they will apply here. Any help is appreciated.
Thank you
Since you ask specifically with a spritekit tag.
Don't use NSTimer or actions to work with time in a game. Instead use the update function. If you're running at 60fps that means the update function will be called 120 times for two seconds. Using the frames instead of seconds to keep your game updated will avoid the gameplay being changed by lag. Imagine for instance that the players game lags a little, in other words runs slower. 2 seconds is still 2 seconds regardless of game lag, so now he is affected less by the glue than a person who has no lag. So...
First off you should have a variable keeping track of in game time: int _time;
In every update cycle you add one to time: _time++;
You should have a variable keeping track of when the user touched the glue: int _glueTouchedAtTime;
When the user clicks glue you set: _glueTouchedAtTime = time;
You should have a constant defining how long the glue is active: #define GLUE_TIME 120;
When you initiate the game set _glueTouchedAtTime to: _glueTouchedAtTime = -GLUE_TIME; To prevent the glue from being on when (_time == 0)
Testing if the user has touched glue now works like this:
if(_glueTouchedAtTime+GLUE_TIME>time) {
// Glue is active
} else {
// Glue is not active
}
Different glues for different sprites
To have different glues for different sprites I would suggest first doing a general game object (GameObject) as a subclass of either SKNode or SKSpriteNode depending on your needs. Then create a subclass of GameObject called GameObjectGluable. This should have a property called: #property int gluedAtTime;
You glue the glueable game object by: aGameObjectGluable.gluedAtTime = time;
Now you can test:
if(aGameObjectGluable.gluedAtTime +GLUE_TIME>time) {
// Game Object is glued
} else {
// Game object is not glued
}
Set your value-of-interest to true and then fire a NSTimer after two seconds to set it back to false.
For an explanation of how you might use NSTimer, see this SO thread: How do I use NSTimer?
You can use SKAction also. The runBlock method let's you execute blocks of code as actions.
SKAction *wait = [SKAction waitForDuration:2.0];
SKAction *reenableJoystick = [SKAction runBlock:^{
joystick.userInteractionEnabled = TRUE;
}];
SKAction *sequence = [SKAction sequence:#[wait, reenableJoystick]];
[self runAction:sequence];

Adding a visual side to a schedule in Cocos2d

I am trying to make a timer for my game that counts down from a number, let's call it 100. I am following the cocos2d best practices, and therefore I am not using a NSTimer. What I am looking to do is that every second, I want to numbers of this timer to change. I could probably find a way to do it using a spritesheet with all of the numbers from 100-0, but I know there is a way to do it using just the numbers 0-9 and their pictures.
This is the code that I am using, with the corresponding -(void)
[self schedule: #selector(tick:)];
[self schedule: #selector(tick2:) interval:1];
All in all, I would like to know how to make it count down from 100, but also to know how to make those ticks decrease the value by 1 every second.
Initialize an integer variable that will keep your countdown value:
int count = 100;
You will want to keep a label (CCLabelBMFont etc) to display this count value. I recommend Glyph Designer (or Hierro if you want something free) to generate the 0 to 9 cocos2D-compatible font bitmaps, which you can then use in your CCLabelBMFont:
CCLabelBMFont* countLabel = [CCLabelBMFont labelWithString:#"0" fntFile:#"myFont.fnt"];
Next, schedule a single tick function that will fire every second:
[self schedule: #selector(tick:) interval:1];
This tick function decrements count by 1 each time it is called. Also, add the condition that if count has reached 0, it will unschedule itself:
-void tick:(ccTime) dt
{
count --; // decrement count by 1 each time this function is called
if (count == 0)
[self unschedule: #selector(tick:)];
}
And finally, in your main update loop (or even in the tick function itself after you decrement your count), you can update and redraw this label with the latest value each time:
[countLabel setString:[NSString stringWithFormat:#"%i", count]];
All the best.

Resources