Search Results

Search found 63 results on 3 pages for 'nstimeinterval'.

Page 1/3 | 1 2 3  | Next Page >

  • Convert a string of numbers to a NSTimeInterval

    - by culov
    I know I must be over-complicating this because it NSTimeInterval is just a double, but I just can't seem to get this done properly since I have had very little exposure to objective c. the scenario is as follows: The data im pulling into the app contains two values, startTime and endTime, which are the epoch times in milliseconds. The variables that I want to hold these values are NSTimeInterval *start; NSTimeInterval *end; I decided to store them as NSTimeIntervals but im thinking that maybe i ought to store them as doubles because theres no need for NSTimeIntervals since comparisons can just be done with a primitive. Either way, I'd like to know what I'm missing in the following step, where I try to convert from string to NSTimeInterval: tempString = [truckArray objectAtIndex:2]; tempDouble = [tempString doubleValue]; Now it's safely stored as a double, but I can't get the value into an NSTimeInterval. How should this be accomplished? Thanks

    Read the article

  • How do I break down an NSTimeInterval into year, months, days, hours, minutes and seconds on iPhone?

    - by willc2
    I have a time interval that spans years and I want all the time components from year down to seconds. My first thought is to integer divide the time interval by seconds in a year, subtract that from a running total of seconds, divide that by seconds in a month, subtract that from the running total and so on. That just seems convoluted and I've read that whenever you are doing something that looks convoluted, there is probably a built-in method. Is there? I integrated Alex's 2nd method into my code. It's in a method called by a UIDatePicker in my interface. NSDate *now = [NSDate date]; NSDate *then = self.datePicker.date; NSTimeInterval howLong = [now timeIntervalSinceDate:then]; NSDate *date = [NSDate dateWithTimeIntervalSince1970:howLong]; NSString *dateStr = [date description]; const char *dateStrPtr = [dateStr UTF8String]; int year, month, day, hour, minute, sec; sscanf(dateStrPtr, "%d-%d-%d %d:%d:%d", &year, &month, &day, &hour, &minute, &sec); year -= 1970; NSLog(@"%d years\n%d months\n%d days\n%d hours\n%d minutes\n%d seconds", year, month, day, hour, minute, sec); When I set the date picker to a date 1 year and 1 day in the past, I get: 1 years 1 months 1 days 16 hours 0 minutes 20 seconds which is 1 month and 16 hours off. If I set the date picker to 1 day in the past, I am off by the same amount. Update: I have an app that calculates your age in years, given your birthday (set from a UIDatePicker), yet it was often off. This proves there was an inaccuracy, but I can't figure out where it comes from, can you?

    Read the article

  • How do I break down an NSTimeInterval into year, months, days, hours, minutes and seconds on iPhone?

    - by willc2
    I have a time interval that spans years and I want all the time components from year down to seconds. My first thought is to integer divide the time interval by seconds in a year, subtract that from a running total of seconds, divide that by seconds in a month, subtract that from the running total and so on. That just seems convoluted and I've read that whenever you are doing something that looks convoluted, there is probably a built-in method. Is there? I integrated Alex's 2nd method into my code. It's in a method called by a UIDatePicker in my interface. NSDate *now = [NSDate date]; NSDate *then = self.datePicker.date; NSTimeInterval howLong = [now timeIntervalSinceDate:then]; NSDate *date = [NSDate dateWithTimeIntervalSince1970:howLong]; NSString *dateStr = [date description]; const char *dateStrPtr = [dateStr UTF8String]; int year, month, day, hour, minute, sec; sscanf(dateStrPtr, "%d-%d-%d %d:%d:%d", &year, &month, &day, &hour, &minute, &sec); year -= 1970; NSLog(@"%d years\n%d months\n%d days\n%d hours\n%d minutes\n%d seconds", year, month, day, hour, minute, sec); When I set the date picker to a date 1 year and 1 day in the past, I get: 1 years 1 months 1 days 16 hours 0 minutes 20 seconds which is 1 month and 16 hours off. If I set the date picker to 1 day in the past, I am off by the same amount. Update: I have an app that calculates your age in years, given your birthday (set from a UIDatePicker), yet it was often off. This proves there was an inaccuracy, but I can't figure out where it comes from, can you?

    Read the article

  • NSTimer timestamp timeinterval question

    - by okami
    I have the following code: [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(timerCount:) userInfo:nil repeats:YES]; -(void)timerCount:(NSTimer *)timer { NSTimeInterval dt = [timer timeInterval]; // do something } The NSTimeInterval I got will be 0.5, the time interval I've put on scheduledTimerWithInterval, this means the timerCount will be called each 0.5 seconds. But I now that there are some stuff as timeStamps, and I want to know if the NSTimer will call the timerCount method in PRECISELY 0.5 seconds each time.

    Read the article

  • obj-c : iphone programming NSTimeInterval problem

    - by the1nz4ne
    hi, i got a problem with my time interval. I need to get the interval of two times in this format : HH:MM. If i enter : 15:35 and 16:35 it is ok, but when i do 20:30 to 01:30, it gives me like 18 hours interval.. anyone have an idea? NSString *startDate= starthere.text; NSString *endDate = endhere.text; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"HH:mm"]; NSDate *dateSelected = [dateFormatter dateFromString:startDate]; NSDate *dateSelected2 = [dateFormatter dateFromString:endDate]; [dateFormatter release]; interval = [dateSelected2 timeIntervalSinceDate:dateSelected];

    Read the article

  • timeIntervalSinceDate Accuracy

    - by mmccomb
    I've been working on a game with an engine that updates 20 times per seconds. I've got to point now where I want to start getting some performance figures and tweak the rendering and logic updates. In order to do so I started to add some timing code to my game loop, implemented as follows... NSDate* startTime = [NSDate date]; // Game update logic here.... // Also timing of smaller internal events NSDate* endTime = [NSDate date]; [endTime timeIntervalSinceDate:startTime]; I noticed however that when I timed blocks within the outer timing logic that the time they took to execute did not sum up to match the overall time taken. So I wrote a small unit test to demonstrate the problem in which I time the overall time taken to complete the test and then 10 smaller events, here it is... - (void)testThatSumOfTimingsMatchesOverallTiming { NSDate* startOfOverallTime = [NSDate date]; // Variable to hold summation of smaller timing events in the upcoming loop... float sumOfIndividualTimes = 0.0; NSTimeInterval times[10] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; for (int i = 0; i < 10; i++) { NSDate* startOfIndividualTime = [NSDate date]; // Kill some time... sleep(1); NSDate* endOfIndividualTime = [NSDate date]; times[i] = [endOfIndividualTime timeIntervalSinceDate:startOfIndividualTime]; sumOfIndividualTimes += times[i]; } NSDate* endOfOverallTime = [NSDate date]; NSTimeInterval overallTimeTaken = [endOfOverallTime timeIntervalSinceDate:startOfOverallTime]; NSLog(@"Sum of individual times: %fms", sumOfIndividualTimes); NSLog(@"Overall time: %fms", overallTimeTaken); STAssertFalse(TRUE, @""); } And here's the output... Sum of individual times: 10.001377ms Overall time: 10.016834ms Which illustrates my problem quite clearly. The overall time was 0.000012ms but the smaller events took only 0.000001ms. So what happened to the other 0.000011ms? Is there anything that looks particularly wrong with my code? Or is there an alternative timing mechanism I should use?

    Read the article

  • Get EXEC_BAD_ACCESS when I get the NSFileModificationDate

    - by Toto
    Hi everyone, I try to get the last modification date of a file: NSFileManager *fm = [[NSFileManager alloc] init]; NSError *err; NSDate *lastModif = [[fm attributesOfItemAtPath:filename error:&err] objectForKey:NSFileModificationDate];//filename is ok ;-) if(err == nil) { [lastModif retain]; //I can put a NSLog of lastModif here, it works !! NSTimeInterval lastModifDiff = [lastModif timeIntervalSinceNow];//crash here } I don't understand why the NSDate seems to be released, why the retain does not retain it. Thank you if you have any idea...

    Read the article

  • How to make UIButton work like Launcher in SpringBoard, when pressed for long timeinterval

    - by KayKay
    In my ViewController I am using UIButton which triggers some action when touchedUpInside. Upto here no problem, but i also want to add another action for touchDown event. More precisely i dont have an idea how to add that action to which event, that will work the same as when App-Icon is pressed longer in springboard which causes springboard enter in editing mode.Actually what i want is : when this button is kept holding for ,say about 2 seconds it will pop-up an alertView without touch being heldUp (with finger is still on button). I have tried with 2 NSdate difference, one of which is allocated when touchedDown and other when touchUpInside. Its working and popping alert,but only after touchedUpInside. I want it to show alert without touch being removed. Here is the code. (IBAction)touchedDown:(id)sender { momentTouchedDown = [[NSDate alloc] init];//class variable NSLog(@"touched down"); } - (IBAction)touchUpInside:(id)sender { NSLog(@"touch lifted Up\n"); NSDate *momentLifted = [[NSDate alloc] init]; double timeInterval = [momentLifted timeIntervalSinceDate:momentTouchedDown]; NSLog(@"time lifted = %@, time down = %@, time diff = %@", momentLifted, momentTouchedDown, [NSString stringWithFormat:@"%g",timeInterval]); [momentLifted release]; if(timeInterval > 2.0) { NSLog(@"AlertBox has been fired"); UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Yes" message:@""//msg delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK" , nil]; [alert show]; [alert release]; } } Please provide me an insight..thanks for help in advance.

    Read the article

  • how can we count the time interval of the animation in cocos2d ?

    - by srikanth rongali
    Hi, I am doing my program in cocos2d. I am using NSDate to get the current time of the start of animation. And I know my animation takes 3 seconds. So I can get the time at completion of animation by using NSInterval and using the previous time and animation time. But, if If the animation time interval is not fixed how can I calculate the time interval of the animation and time at the completion of the animation ? I am animating a sprite. Please help how can I make it. Thank You.

    Read the article

  • Converting a constantly changing scalar value to a changing interval or frequency

    - by eco_bach
    Although I'm coding in Objective C, this is more of a general programming question. What is the best way to convert a constantly changing scalar value to a changing interval or frequency? Right now every time the scalar value changes I am destroying the NSInterval ie [self.myTimer invalidate]; self.myTimer = nil; and creating a new one, but this seems like a VERY expensive way to achieve my goal, since the changing scalar value in my case represents the horizontal velocity of a swipe. For a rough analogy, think of the speed of a swipe being reflected in a visual metronome, the faster you swipe, the higher(shorter interval) the frequency of the metronome.

    Read the article

  • Converting 'x' value of a CGPoint ivar to NSTimeInterval?

    - by eco_bach
    Hi I have a velocity ivar defined as a CGPoint. I need to somehow extract just the 'x' value of velocity, and then use this to call-send a message to the following method signature -(void) adjustTimer:(NSTimeInterval*)newInterval How do I obtain just the 'x' value of a CGPoint? Do I then need to convert or cast this result before calling my adjustTimer method?

    Read the article

  • How to render consistence and smooth moving animation on iphone / ipod / iphone simulator.

    - by shakthi
    I am trying render a simple animation(object movement animations) on iphone. I used opengl for object rendering. Movements appears to be smooth on the simulator. But if I used same code in the ipod, object movement is slower. In the iphone it is still slower. I googled a bit and found 'frame rate independent rendering method', which taught me the concept of 'time interval' and object movement based on it. However result is very unpleasant. There is a lot of jerk in the animation even when fps remains above 20. Following code fragment is used for calculation of time interval between successive frames and I am using that to move my animation. NSTimeInterval GetTimeIntervals(NSTimeInterval * inLastElapsedTime ) { NSTimeInterval intervalTime = 0; NSTimeInterval currentTime = [NSDate timeIntervalSinceReferenceDate]; if(*inLastElapsedTime != 0 ) { intervalTime = currentTime - *inLastElapsedTime; } *inLastElapsedTime = currentTime; return intervalTime; }

    Read the article

  • NSDate - GMT on iPhone

    - by Mick Walker
    I have the following code in a production application which calculates a GMT date from the date the user enters: NSDate *localDate = pickedDate; NSTimeInterval timeZoneOffset = [[NSTimeZone defaultTimeZone] secondsFromGMT]; // You could also use the systemTimeZone method NSTimeInterval gmtTimeInterval = [localDate timeIntervalSinceReferenceDate] - timeZoneOffset; NSDate *gmtDate = [NSDate dateWithTimeIntervalSinceReferenceDate:gmtTimeInterval]; The code was working fine, until the dreaded daylight savings time came into force in the UK last week. How can I convert the date into GMT whilst taking into account daylight savings?

    Read the article

  • iPhone SDK: TextView, Keyboard in Landscape mode

    - by Arnold
    Hello. How do I make sure that the textview is shown and the keyboard is not obscuring the textview, while in landscape. Using UICatalog I created a TextViewController which works. In it there are two methods for calling the keyboard and making sure that textView is positioned above the keyboard. his just works great in Portrait mode. I got the Landscape mode working, but on the textView is still being put to the top of the iPhone to compensate for the keyboard in portrait mode. I changed the methods for showing the keyboards. Below is the code for this methods: (I will just let see the code for show, since the hide code will be the reverse.. - (void)keyboardWillShow:(NSNotification *)aNotification { UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation]; if (orientation == UIInterfaceOrientationPortrait) { // the keyboard is showing so resize the table's height CGRect keyboardRect = [[[aNotification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] CGRectValue]; NSTimeInterval animationDuration = [[[aNotification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]; CGRect frame = self.view.frame; frame.size.height -= keyboardRect.size.height; [UIView beginAnimations:@"ResizeForKeyboard" context:nil]; [UIView setAnimationDuration:animationDuration]; self.view.frame = frame; [UIView commitAnimations]; } else if (orientation == UIInterfaceOrientationLandscapeLeft) { NSLog(@"Left"); // Verijderen later CGRect keyboardRect = [[[aNotification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] CGRectValue]; NSTimeInterval animationDuration = [[[aNotification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]; CGRect frame = self.view.frame; frame.size.width -= keyboardRect.size.height; [UIView beginAnimations:@"ResizeForKeyboard" context:nil]; [UIView setAnimationDuration:animationDuration]; self.view.frame = frame; [UIView commitAnimations]; } else if (orientation == UIInterfaceOrientationLandscapeRight){ NSLog(@"Right"); // verwijderen later. CGRect keyboardRect = [[[aNotification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] CGRectValue]; NSTimeInterval animationDuration = [[[aNotification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]; CGRect frame = self.view.frame; frame.size.width -= keyboardRect.size.width; [UIView beginAnimations:@"ResizeForKeyboard" context:nil]; [UIView setAnimationDuration:animationDuration]; self.view.frame = frame; [UIView commitAnimations]; } } I know that I have to change the line frame.size.height -= keyboardRect.size.height but I do not seem to get it working. I tried frame.size.width -= keyboardRect.size.height that did not work. Losing the keyboardRect and frame all together work, however off course the keyboard obscures the textview........

    Read the article

  • How to compare two times in milliseconds precision?

    - by Marcos Issler
    I have a subtitle text file that works with standart srt format 00:00:00,000 Hour, minutes, seconds, milliseconds. I want to create a timer to update the subtitle screen and check the current time to know what subtitle show on screen. Which is the best to use? NSTimeInterval, NSDate? I think the best is to convert all to times to milliseconds number and compare. But NSTimeInterval works with seconds, not milliseconds. Some clue? Marcos

    Read the article

  • NSMutableDictionary of NSMutableSets... sorting this out

    - by Mike
    I have a NSMutableDictionary of NSMutableSets. Each set entry is a string, something like this: NSMutableSet *mySet = [NSMutableSet setWithObjects: [NSString stringWithFormat:@"%d", time1], [NSString stringWithFormat:@"%d", time2], [NSString stringWithFormat:@"%d", time3], nil]; // time 1,2,3, are NSTimeInterval variables then I store each set on the dictionary using this: NSString *rightNowString = [NSString stringWithFormat:@"%d", rightNow]; [myDict setValue:mySet forKey:rightNow]; // rightNow is NSTimeInterval as rightNow key can occur out of order, I end with a NSDictionary that is not ordered by rightNow. How can I sort this NSDictionary by its keys considering that they are numbers stored as strings on the dictionary...? I don't care for ordering the sets, just the dictionary. thanks for any help.

    Read the article

  • iPad start in Landscape receive only touch within 768x768

    - by user1307179
    It works perfect fine when starting in portrait and also works when you rotate from portrait to landscape and back. It does not work when starting in landscape. But then it works when you rotate from landscape to portrait and back. In landscape starting mode, the screen does not respond with any touch where screen coordinateX greater than 768. What happens in code is, I use status bar orientation to determine original orientation and rotate each view manually. The views display correctly but does not receive touch properly. Then my root view controller will get called when ipad start rotating with: - (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration which will rotate every subviews. Root controller: - (void)loadView { self.view = [[UIView alloc]init ]; //initialize child views [self willRotateToInterfaceOrientation:0 duration:0]; } - (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration { if ([model isLandscape]) { self.view.frame = CGRectMake(0, 0, 1024, 768-80); } else { self.view.frame = CGRectMake(0, 0, 768, 1024-80); } //rotate child views } My code [model isLandscape] works so I don't need to provide details as to how it works but here are the code anyway: - (bool)isLandscape { if (orientation == UIInterfaceOrientationLandscapeLeft || orientation == UIInterfaceOrientationLandscapeRight) return true; else return false; } -(id) init { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:) name:UIDeviceOrientationDidChangeNotification object:nil]; } - (void)orientationChanged:(NSNotification *)notification { UIInterfaceOrientation curOrientation = [[UIDevice currentDevice] orientation]; if (curOrientation == UIDeviceOrientationPortrait || curOrientation == UIDeviceOrientationPortraitUpsideDown || curOrientation == UIDeviceOrientationLandscapeLeft || curOrientation == UIDeviceOrientationLandscapeRight) { orientation = curOrientation; ((AppDelegate*)([UIApplication sharedApplication].delegate)).savedOrientationForRestart = orientation; NSLog(@"changed"); } } -(void)validateOrientation { //first time when initializing orientation UIInterfaceOrientation curOrientation = [[UIDevice currentDevice] orientation]; if (curOrientation != UIDeviceOrientationPortrait && curOrientation != UIDeviceOrientationPortraitUpsideDown && curOrientation != UIDeviceOrientationLandscapeLeft && curOrientation != UIDeviceOrientationLandscapeRight) { orientation = [[UIApplication sharedApplication] statusBarOrientation]; } }

    Read the article

  • How to Make a Game like Space Invaders - Ray Wenderlich (why do my space invaders scroll off screen)

    - by Erv Noel
    I'm following this tutorial(http://www.raywenderlich.com/51068/how-to-make-a-game-like-space-invaders-with-sprite-kit-tutorial-part-1) and I've run into a problem right after the part where I add [self determineInvaderMovementDirection]; to my GameScene.m file (specifically to my moveInvadersForUpdate method) The tutorial states that the space invaders should be moving accordingly after adding this piece of code but when I run they move to the left and they do not come back. I'm not sure what I am doing wrong as I have followed this tutorial very carefully. Any help or clarification would be greatly appreciated. Thanks in advance ! Here is the full GameScene.m #import "GameScene.h" #import <CoreMotion/CoreMotion.h> #pragma mark - Custom Type Definitions /* The type definition and constant definitions 1,2,3 take care of the following tasks: 1.Define the possible types of invader enemies. This can be used in switch statements later when things like displaying different sprites images for each enemy type. The typedef makes InvaderType a formal Obj-C type that is type checked for method arguments and variables.This is so that the wrong method argument is not used or assigned to the wrong variable. 2. Define the size of the invaders and that they'll be laid out in a grid of rows and columns on the screen. 3. Define a name that will be used to identify invaders when searching for them. */ //1 typedef enum InvaderType { InvaderTypeA, InvaderTypeB, InvaderTypeC } InvaderType; /* Invaders move in a fixed pattern: right, right, down, left, down, right right. InvaderMovementDirection tracks the invaders' progress through this pattern */ typedef enum InvaderMovementDirection { InvaderMovementDirectionRight, InvaderMovementDirectionLeft, InvaderMovementDirectionDownThenRight, InvaderMovementDirectionDownThenLeft, InvaderMovementDirectionNone } InvaderMovementDirection; //2 #define kInvaderSize CGSizeMake(24,16) #define kInvaderGridSpacing CGSizeMake(12,12) #define kInvaderRowCount 6 #define kInvaderColCount 6 //3 #define kInvaderName @"invader" #define kShipSize CGSizeMake(30, 16) //stores the size of the ship #define kShipName @"ship" // stores the name of the ship stored on the sprite node #define kScoreHudName @"scoreHud" #define kHealthHudName @"healthHud" /* this class extension allows you to add “private” properties to GameScene class, without revealing the properties to other classes or code. You still get the benefit of using Objective-C properties, but your GameScene state is stored internally and can’t be modified by other external classes. As well, it doesn’t clutter the namespace of datatypes that your other classes see. This class extension is used in the method didMoveToView */ #pragma mark - Private GameScene Properties @interface GameScene () @property BOOL contentCreated; @property InvaderMovementDirection invaderMovementDirection; @property NSTimeInterval timeOfLastMove; @property NSTimeInterval timePerMove; @end @implementation GameScene #pragma mark Object Lifecycle Management #pragma mark - Scene Setup and Content Creation /*This method simply invokes createContent using the BOOL property contentCreated to make sure you don’t create your scene’s content more than once. This property is defined in an Objective-C Class Extension found near the top of the file()*/ - (void)didMoveToView:(SKView *)view { if (!self.contentCreated) { [self createContent]; self.contentCreated = YES; } } - (void)createContent { //1 - Invaders begin by moving to the right self.invaderMovementDirection = InvaderMovementDirectionRight; //2 - Invaders take 1 sec for each move. Each step left, right or down // takes 1 second. self.timePerMove = 1.0; //3 - Invaders haven't moved yet, so set the time to zero self.timeOfLastMove = 0.0; [self setupInvaders]; [self setupShip]; [self setupHud]; } /* Creates an invade sprite of a given type 1. Use the invadeType parameterr to determine color of the invader 2. Call spriteNodeWithColor:size: of SKSpriteNode to alloc and init a sprite that renders as a rect of the given color invaderColor with size kInvaderSize */ -(SKNode*)makeInvaderOfType:(InvaderType)invaderType { //1 SKColor* invaderColor; switch (invaderType) { case InvaderTypeA: invaderColor = [SKColor redColor]; break; case InvaderTypeB: invaderColor = [SKColor greenColor]; break; case InvaderTypeC: invaderColor = [SKColor blueColor]; break; } //2 SKSpriteNode* invader = [SKSpriteNode spriteNodeWithColor:invaderColor size:kInvaderSize]; invader.name = kInvaderName; return invader; } -(void)setupInvaders { //1 - loop over the rows CGPoint baseOrigin = CGPointMake(kInvaderSize.width / 2, 180); for (NSUInteger row = 0; row < kInvaderRowCount; ++row) { //2 - Choose a single InvaderType for all invaders // in this row based on the row number InvaderType invaderType; if (row % 3 == 0) invaderType = InvaderTypeA; else if (row % 3 == 1) invaderType = InvaderTypeB; else invaderType = InvaderTypeC; //3 - Does some math to figure out where the first invader // in the row should be positioned CGPoint invaderPosition = CGPointMake(baseOrigin.x, row * (kInvaderGridSpacing.height + kInvaderSize.height) + baseOrigin.y); //4 - Loop over the columns for (NSUInteger col = 0; col < kInvaderColCount; ++col) { //5 - Create an invader for the current row and column and add it // to the scene SKNode* invader = [self makeInvaderOfType:invaderType]; invader.position = invaderPosition; [self addChild:invader]; //6 - update the invaderPosition so that it's correct for the //next invader invaderPosition.x += kInvaderSize.width + kInvaderGridSpacing.width; } } } -(void)setupShip { //1 - creates ship using makeShip. makeShip can easily be used later // to create another ship (ex. to set up more lives) SKNode* ship = [self makeShip]; //2 - Places the ship on the screen. In SpriteKit the origin is at the lower //left corner of the screen. The anchorPoint is based on a unit square with (0, 0) at the lower left of the sprite's area and (1, 1) at its top right. Since SKSpriteNode has a default anchorPoint of (0.5, 0.5), i.e., its center, the ship's position is the position of its center. Positioning the ship at kShipSize.height/2.0f means that half of the ship's height will protrude below its position and half above. If you check the math, you'll see that the ship's bottom aligns exactly with the bottom of the scene. ship.position = CGPointMake(self.size.width / 2.0f, kShipSize.height/2.0f); [self addChild:ship]; } -(SKNode*)makeShip { SKNode* ship = [SKSpriteNode spriteNodeWithColor:[SKColor greenColor] size:kShipSize]; ship.name = kShipName; return ship; } -(void)setupHud { //Sets the score label font to Courier SKLabelNode* scoreLabel = [SKLabelNode labelNodeWithFontNamed:@"Courier"]; //1 - Give the score label a name so it becomes easy to find later when // the score needs to be updated. scoreLabel.name = kScoreHudName; scoreLabel.fontSize = 15; //2 - Color the score label green scoreLabel.fontColor = [SKColor greenColor]; scoreLabel.text = [NSString stringWithFormat:@"Score: %04u", 0]; //3 - Positions the score label near the top left corner of the screen scoreLabel.position = CGPointMake(20 + scoreLabel.frame.size.width/2, self.size.height - (20 + scoreLabel.frame.size.height/2)); [self addChild:scoreLabel]; //Applies the font of the health label SKLabelNode* healthLabel = [SKLabelNode labelNodeWithFontNamed:@"Courier"]; //4 - Give the health label a name so it can be referenced later when it needs // to be updated to display the health healthLabel.name = kHealthHudName; healthLabel.fontSize = 15; //5 - Colors the health label red healthLabel.fontColor = [SKColor redColor]; healthLabel.text = [NSString stringWithFormat:@"Health: %.1f%%", 100.0f]; //6 - Positions the health Label on the upper right hand side of the screen healthLabel.position = CGPointMake(self.size.width - healthLabel.frame.size.width/2 - 20, self.size.height - (20 + healthLabel.frame.size.height/2)); [self addChild:healthLabel]; } #pragma mark - Scene Update - (void)update:(NSTimeInterval)currentTime { //Makes the invaders move [self moveInvadersForUpdate:currentTime]; } #pragma mark - Scene Update Helpers //This method will get invoked by update -(void)moveInvadersForUpdate:(NSTimeInterval)currentTime { //1 - if it's not yet time to move, exit the method. moveInvadersForUpdate: // is invoked 60 times per second, but you don't want the invaders to move // that often since the movement would be too fast to see if (currentTime - self.timeOfLastMove < self.timePerMove) return; //2 - Recall that the scene holds all the invaders as child nodes; which were // added to the scene using addChild: in setupInvaders identifying each invader // by its name property. Invoking enumerateChildNodesWithName:usingBlock only loops over the invaders because they're named kInvaderType; which makes the loop skip the ship and the HUD. The guts og the block moves the invaders 10 pixels either right, left or down depending on the value of invaderMovementDirection [self enumerateChildNodesWithName:kInvaderName usingBlock:^(SKNode *node, BOOL *stop) { switch (self.invaderMovementDirection) { case InvaderMovementDirectionRight: node.position = CGPointMake(node.position.x - 10, node.position.y); break; case InvaderMovementDirectionLeft: node.position = CGPointMake(node.position.x - 10, node.position.y); break; case InvaderMovementDirectionDownThenLeft: case InvaderMovementDirectionDownThenRight: node.position = CGPointMake(node.position.x, node.position.y - 10); break; InvaderMovementDirectionNone: default: break; } }]; //3 - Record that you just moved the invaders, so that the next time this method is invoked (1/60th of a second from when it starts), the invaders won't move again until the set time period of one second has elapsed. self.timeOfLastMove = currentTime; //Makes it so that the invader movement direction changes only when the invaders are actually moving. Invaders only move when the check on self.timeOfLastMove passes (when conditional expression is true) [self determineInvaderMovementDirection]; } #pragma mark - Invader Movement Helpers -(void)determineInvaderMovementDirection { //1 - Since local vars accessed by block are default const(means they cannot be changed), this snippet of code qualifies proposedMovementDirection with __block so that you can modify it in //2 __block InvaderMovementDirection proposedMovementDirection = self.invaderMovementDirection; //2 - Loops over the invaders in the scene and refers to the block with the invader as an argument [self enumerateChildNodesWithName:kInvaderName usingBlock:^(SKNode *node, BOOL *stop) { switch (self.invaderMovementDirection) { case InvaderMovementDirectionRight: //3 - If the invader's right edge is within 1pt of the right edge of the scene, it's about to move offscreen. Sets proposedMovementDirection so that the invaders move down then left. You compare the invader's frame(the frame that contains its content in the scene's coordinate system) with the scene width. Since the scene has an anchorPoint of (0,0) by default and is scaled to fill it's parent view, this comparison ensures you're testing against the view's edges. if (CGRectGetMaxX(node.frame) >= node.scene.size.width - 1.0f) { proposedMovementDirection = InvaderMovementDirectionDownThenLeft; *stop = YES; } break; case InvaderMovementDirectionLeft: //4 - If the invader's left edge is within 1 pt of the left edge of the scene, it's about to move offscreen. Sets the proposedMovementDirection so invaders move down then right if (CGRectGetMinX(node.frame) <= 1.0f) { proposedMovementDirection = InvaderMovementDirectionDownThenRight; *stop = YES; } break; case InvaderMovementDirectionDownThenLeft: //5 - If invaders are moving down then left, they already moved down at this point, so they should now move left. proposedMovementDirection = InvaderMovementDirectionLeft; *stop = YES; break; case InvaderMovementDirectionDownThenRight: //6 - if the invaders are moving down then right, they already moved down so they should now move right. proposedMovementDirection = InvaderMovementDirectionRight; *stop = YES; break; default: break; } }]; //7 - if the proposed invader movement direction is different than the current invader movement direction, update the current direction to the proposed direction if (proposedMovementDirection != self.invaderMovementDirection) { self.invaderMovementDirection = proposedMovementDirection; } } #pragma mark - Bullet Helpers #pragma mark - User Tap Helpers #pragma mark - HUD Helpers #pragma mark - Physics Contact Helpers #pragma mark - Game End Helpers @end

    Read the article

  • iPad orientation on launch problem in portrait (bottom home button)

    - by edie
    Hi.... I've an iPad app that supports all orientation... my problem was on the start up of the application. In case of landScapeRight and landScapeLeft and portrait(top home button) the views shows correctly but when the app start in portrait (bottom home button) the views show in landscape mode... I've implemented the - (void) willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation When I change the apps orientation the views shows correctly.

    Read the article

1 2 3  | Next Page >