Game Development Reference
In-Depth Information
{
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);
}
This looks like math. Smells like geometry. And it's good for your health! Okay, I guess I
need a more convincing argument. Okay: it's really simple! Better?
The first two lines are just setup code to assign the size of the view to
viewSize
, which
is equal to the size of the screen in points. And then the center point of the view is calcu-
lated and assigned to
viewCenter
. No troublesome math there.
The
viewPos
variable is initialized with the target's
positionInPoints
with the
viewCenter
subtracted from it. This subtraction with the
ccpSub
function is what
keeps the target node centered in the view. If you didn't do that, scrolling would still func-
tion but the target node would appear at the lower-left corner of the screen.
Tip
The
ccpSub
function along with others carrying the
ccp
prefix are de-
clared in the
CGPointExtension.h
header file. You will find this file in the
Xcode project under
libs/cocos2d-ios.xcodeproj/cocos2d/Sup-
port/Math
. The
ccp
functions perform many commonly needed vector math
operations, like add, subtract, multiply, dot product, or calculate the distance
between two points.
Worth noting is the use of
positionInPoints
rather than
position
. The
posi-
tion
values are interpreted differently based on a node's
positionType
prop-
erty—for instance, if the node's
positionType
is set in SpriteBuilder to “percent in
parent container,” the position value range is typically in the order of 0.0 to 1.0. The
po-
sitionInPoints
property converts the position based on
positionType
and re-
Search WWH ::
Custom Search