Touch Handling in Cocos2D 3.x(五)

Touch Handling in Cocos2D 3.x(五),第1张

概述实现新英雄的放置功能 首先我们需要一个变量来保持我们当前移动英雄的引用,因此我们将添加一个私有实例变量.修改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' spriteCCSprite *hero = [CCSprite spriteWithImagenamed:@"hero.png"];[self addChild:hero];// place the sprite at the touch locationhero.position = touchLocation;

替换为如下代码:

// create a 'hero' spritecurrentHero = [CCSprite spriteWithImagenamed:@"hero.png"];[self addChild:currentHero];// place the sprite at the touch locationcurrentHero.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中掌控触摸处理.

总结

以上是内存溢出为你收集整理的Touch Handling in Cocos2D 3.x(五)全部内容,希望文章能够帮你解决Touch Handling in Cocos2D 3.x(五)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1073618.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-26
下一篇 2022-05-26

发表评论

登录后才能评论

评论列表(0条)

保存