首页 技术 正文
技术 2022年11月15日
0 收藏 826 点赞 2,725 浏览 1258 个字

实现新英雄的放置功能

首先我们需要一个变量来保持我们当前移动英雄的引用,因此我们将添加一个私有实例变量.修改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中掌控触摸处理.

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,000
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,512
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,358
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,141
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,771
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,849