SpriteBuilder study NOTE 2: spritebuilder

Source: Internet
Author: User

SpriteBuilder study NOTE 2: spritebuilder

Chapter 3 Controlling and Scrolling

@implementation GameScene {    __weak CCNode *_levelNode;    __weak CCPhysicsNode *_physicalNode;    __weak CCNode *_playerNode;    __weak CCNode *_backgroundNode;}

Note the _ weak keyword. In general, when declaring an obejct pointer variable instead of the created or owned class, it is best to use _ weak, especially in cocos2d, which should always declare a reference, when this reference is not a "sibling" (sibling) of the parent or node. If no _ weak keyword exists, a strong reference is generated by default.

Find the Player Node by name

Add code to GameScene:

-(Void) didLoadFromCCB {NSLog (@ "GameScene created! "); // Enable acceptable input events // This sentence allows the GameScene class to accept the touch event self. userInteractionEnabled = YES; // load the current level to load the current level [self loadLevelNamed: nil];}
-(Void) loadLevelNamed :( NSString *) levelCCB {// obtain the player of the current level in scene and recursively search for _ playerNode = [self getChildByName: @ "player" recursively: YES]; // if not found, NSAssert will throw an exception NSAssert1 (_ playerNode, @ "player node not found in level: % @", levelCCB );}

The following code is used to move an object to the position of the touch by touching it.

- (void)touchBegan:(CCTouch*)touch withEvent:(UIEvent*)event {    _playerNode.position = [touch locationInNode:self];}

NOTE: When the first parameter type in the book is UITouch *, an error is reported. You can change it to CCTouch to implement the function.

Check the API and extract it as follows:

TouchBegan: withEvent:

Called when a touch began. Behavior notes:

- (void)touchBegan:(CCTouch *)touch withEvent:(CCTouchEvent *)eventParameters
Touch

Contains the touch.

Event

Current event information.

Discussion
  • If a touch is dragged inside a node which does not claim user interaction, a touchBegan event will be generated.
  • If node has exclusive touch, all other ongoing touches will be canceled.
  • If a node wants to handle any touch event, the touchBegan method must be overridden in the node subclass. Overriding just touchMoved or touchEnded does not suffice.
  • To pass the touch further down the Cocos2D responder chain, call the super implementation, ie [super touchBegan: withEvent:].
See Also
  • CCTouch, CCTouchEvent

Declared In CCResponder.h

 

Allocate Level-Node Variables

Assigning variables in SpriteBuilder is the same as getting a node by name. It is just a matter of personal habits. However, it is not recommended to use getChildByName frequently: The method is in schedule methond (not familiar with the method) and updata: method, especially recursive search and a deep-node hierarch.

Caution: allocating a variable in SpriteBuilder is only applicable to direct descendants of the CCB File (descendant-do not know how to translate) another imported CCB instance specifies node as a variable or properties. This is why the player node is obtained by name.

Open GameScene. ccb,

 

Note: A doc root var assigns a node to a correspondingly named ivar or property declared in the CCB root node's custom class

Doc root var: assign a node to the variable or attribute of the corresponding name declared in the Custom class of the CCB root node.

After this step, the _ levelNode variable will be allocated by CCBReader before it sends the didLoadFromCCB message. This is the simplest and most effective method to create a node contained in CCB.

 

Move Player with CCActionMoveTo

To smoothly move the player to a specified position, you can modify the following code:

- (void)touchBegan:(CCTouch*)touch withEvent:(UIEvent*)event {   // _playerNode.position = [touch locationInNode:self];    CGPoint pos = [touch locationInNode:_levelNode];    CCAction *move = [CCActionMoveTo actionWithDuration:0.2 position:pos];    [_playerNode runAction:move];}

The touch point is converted according to _ levelNode. This is important to ensure that the player can move on the entire _ levelNode, rather than being banned from the screen space. However, this cannot be seen yet, because scrolling has not been added ).

However, if you increase the duration, you will find that the Moving action is not superimposed and the player will not be parked in the last place you click. Therefore, you must add a tag. With this tag, you can stop the current action before executing the new action. The code change is as follows:

- (void)touchBegan:(CCTouch*)touch withEvent:(UIEvent*)event {   // _playerNode.position = [touch locationInNode:self];    [_playerNode stopActionByTag:1];    CGPoint pos = [touch locationInNode:_levelNode];    CCAction *move = [CCActionMoveTo actionWithDuration:20.2 position:pos];    move.tag = 1;    [_playerNode runAction:move];}

 

Scrolling the Level)

In 2D games, the more common practice is to move the content layer in the opposite direction, and the scrolling effect has been achieved.

In Cocos2D and OpenGl, there is no camera concept, and only the device screen is used ).

 

Scheduling Updates (Scheduled Update)

If player is moved to the right and Top, what we need to do is to move _ levelNode to the left and bottom. The position of the player is limited to level node, and the left side of the lower left corner is (0, 0). In this program, the range is 4000*500 points.

Add the following code to GameScene:

// The updata: method is automatically called once per frame // the update method is automatically called at each frame-(void) update :( CCTime) delta {// update scroll node position to player node, with offset to center player in the view [self scrollToTarget: _ playerNode];}

Update: The method is automatically called by Cocos2d. At the underlying layer, each frame and node appear before the screen are called again.

Unlike the previous Cocos2d version, you no longer need to explicitly schedule updates (you no longer have to explicitly schedule the update: method .)

You can use the node schedule and unschedule methods to schedule other methods or blocks. (you can still schedule other methods or blocks using the node schedule and unschedule methods)

For example, to run a selector with a delay, you can write it as follows:

[Self scheduleOnce: @ selector (theDelayedMethod :) delay: 2.5]:

Then implement the corresponding selector in the same class. This selector must use a CCTime parameter:

-(Void) theDelayedMethod :( CCTime) delta {

// Your code

}

Caution: Never use nsttion. These time methods are not automatically paused when node or Cocos2d is paused.

The delta parameter is delta time or difference in time.

At 60 frames per second, the delta time is usually about 0.0167 in seconds.

Delta time is usually used to move nodes at the same speed, ignoring the frame rate. We do not use delta time in this book, because we use the Cocos2d physical engine.

 

Moving the level Node in the Opposite Derection

Move Level Node in the opposite direction

Add the scrollToTarget method to GameScene. m to complete scrolling:

- (void)scrollToTarget:(CCNode*)target {    CGSize viewSize = [CCDirector sharedDirector].viewSize;    CGPoint viewCenter = CGPointMake(viewSize.width / 2.0,viewSize.height / 2.0);    CGPoint viewPos = ccpSub(target.positionInPoints, viewCenter);    CGSize levelSize = _levelNode.contentSizeInPoints;    viewPos.x = MAX(0.0, MIN(viewPos.x, levelSize.width - viewSize.width));    viewPos.y = MAX(0.0,MIN(viewPos.y, levelSize.height - viewSize.height));    _levelNode.positionInPoints = ccpNeg(viewPos);}

The first two rows are used to specify the size of the view to the viewSize. The value is the value in the unit of points.

Then calculate the center of the view.

The viewPos variable is initialized to the positionInPoints of the target minus the center point viewCenter.

This Subtraction using ccpSub is to keep the target node in the center position. If this step is not performed, the target node will disappear in the lower left corner of the screen.

The levelSize variable is defined as _ lovelNode. contentSizeInPoints. In the following two rows, it is used to hold viewPos.

Because the screen should never be closer to the level boundary than the viewCenter scrolling, subtraction is used. The distance of each boundary is equal to viewSize. In other words, the area that can be rolled is twice that of viewCenter or a viewSize ???

Relationship between the level Area and the scrollable area: the arrow indicates the scrollable area. Note that the player is no longer in the center when it is close to the level boundary.

D Not complete to be continued d

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.