cocos2d-iphone之魔塔20层第三部分
首先我们要添加一个方向控制器,首先在Game01这个类头文件中定义定义四个属性[html]
@property (nonatomic,retain) CCSprite *btnup;
@property (nonatomic,retain) CCSprite *btndown;
@property (nonatomic,retain) CCSprite *btnleft;
@property (nonatomic,retain) CCSprite *btnright;
在定义一个实例变量CCSprite *btnnormal;
然后在Game01.m文件中定义两个全局变量
[html]
//移动方向
int direction;
CGPoint point;
在初始化方法里添加如下代码
[html]
//方向控制
point = CGPointMake(size.width - 110, 75);
btnnormal = [CCSprite spriteWithFile:@"btn_normal.png"];
self.btnup = [CCSprite spriteWithFile:@"btn_up.png"];
self.btndown = [CCSprite spriteWithFile:@"btn_down.png"];
self.btnleft = [CCSprite spriteWithFile:@"btn_left.png"];
self.btnright = [CCSprite spriteWithFile:@"btn_right.png"];
btnnormal.position = self.btnup.position = self.btndown.position = self.btnleft.position = self.btnright.position = point;
[self addChild:btnnormal];
然后再添加其响应事件在这里我指定了四个区域,分别响应上下左右移动事件,点击不同的区域就
切换不同的控制器图片
[html]
#pragma mark - 游戏中的触摸响应事件
-(BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
//获取触摸点位置
CGPoint touchLocation = [self convertTouchToNodeSpace:touch];
//获取矩形区域
CGRect Rect = CGRectMake(touchLocation.x,
touchLocation.y,
1,
1);
CGRect RectUp = CGRectMake(point.x - 20,
point.y + 20,
40,
65);
CGRect RectDown = CGRectMake(point.x - 20,
point.y - 85,
40,
65);
CGRect RectLeft = CGRectMake(point.x - 85,
point.y - 20,
65,
40);
CGRect RectRight = CGRectMake(point.x + 20,
point.y - 20,
65,
40);
if (!_hero.isFighting)
{
direction = 0;
//检测触点是否在控件区
if (CGRectIntersectsRect(Rect, RectUp))
{
direction = 1;
curbtn = self.btnup;
[self addChild:self.btnup];
}
if (CGRectIntersectsRect(Rect, RectDown))
{
direction = 2;
curbtn = btndown;
[self addChild:btndown];
}
if (CGRectIntersectsRect(Rect, RectLeft))
{
direction = 3;
curbtn = btnleft;
[self addChild:btnleft];
}
if (CGRectIntersectsRect(Rect, RectRight))
{
direction = 4;
curbtn = btnright;
[self addChild:btnright];
}
}
return YES;
}
-(void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event
{
direction = 0;
[self removeChild:curbtn cleanup:YES];
}
不要忘记在初始化方法返回前开启触摸,这里我使用来[[CCTouchDispatchersharedDispatcher]addTargetedDelegate:selfpriority:0swallowsTouches:YES];
开启触摸事件
到了这里你会发现勇士还是不会移动,那么接下来我们就让控制器和勇士的移动联系起来
我用一个更新方法来更新勇士的移动位置
[html]
-(void)updateMove
{
CGPoint playerPoint = _hero.position;
switch (direction)
{
case 1:
playerPoint = CGPointMake(playerPoint.x, playerPoint.y + 32*_scale);
break;
case 2:
playerPoint = CGPointMake(playerPoint.x, playerPoint.y - 32*_scale);
break;
case 3:
playerPoint = CGPointMake(playerPoint.x - 32*_scale, playerPoint.y);
break;
<补充:移动开发 , 其他 ,