加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Touch Handling in Cocos2D 3.x(五)

发布时间:2020-12-14 16:41:01 所属栏目:百科 来源:网络整理
导读:实现新英雄的放置功能 首先我们需要一个变量来保持我们当前移动英雄的引用,因此我们将添加一个私有实例变量.修改MainScene.m中的代码. 用: @implementation MainScene { // this is the section to place private instance variables! CCSprite *currentHero

实现新英雄的放置功能

首先我们需要一个变量来保持我们当前移动英雄的引用,因此我们将添加一个私有实例变量.修改MainScene.m中的代码.

用:

@implementation MainScene {
    // this is the section to place private instance variables!
    CCSprite *currentHero;
}

替换原来的代码:

@implementation MainScene

现在我们有了一个新的私有变量.该变量将总是持有我们当前拖拽英雄的引用,所以我们可以在屏幕触摸移动时更新它的位置.让我们开始在touchBegan方法中赋值该变量.

将以下代码:

// create a 'hero' sprite
CCSprite *hero = [CCSprite spriteWithImageNamed:@"hero.png"];
[self addChild:hero];
// place the sprite at the touch location
hero.position = touchLocation;

替换为如下代码:

// create a 'hero' sprite
currentHero = [CCSprite spriteWithImageNamed:@"hero.png"];
[self addChild:currentHero];
// place the sprite at the touch location
currentHero.position = touchLocation;

现在当前英创建的同时它的引用也被存储下来.这使得我们可以在整个对象中访问最后创建的英雄并且可以实现其他触摸方法.

当用户在屏幕上移动手指时,我们想要移动刚创建的英雄.因此我们需要实现touchMoved方法,该方法在每次触摸改变位置时被调用.增加该方法到MainScene.m中:

- (void)touchMoved:(UITouch *)touch withEvent:(UIEvent *)event { CGPoint touchLocation = [touch locationInNode:self]; currentHero.position = touchLocation;
}

它到底做了什么?每次触摸移动时我们取得触摸的位置并且移动刚才创建的英雄到新的位置.

我们最后一步是当触摸结束或被取消时去复位英雄的引用,因为我们只想保持当前选择英雄的引用.添加如下2个方法到MainScene.m中去:

- (void)touchEnded:(UITouch *)touch withEvent:(UIEvent *)event { currentHero = nil; } - (void)touchCancelled:(UITouch *)touch withEvent:(UIEvent *)event { currentHero = nil; }

现在你可以再次build和运行你的项目.游戏的行为应该精确和算法轮廓相匹配,并且你应该看到如下画面:

做的不错!你的下一步将是更仔细的在Cocos2d 3.0中掌控触摸处理.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读