(转载请注明出处:http://blog.csdn.net/buptgshengod)
1.介绍
cocos2d为我们提供了好用的摇杆控制器,主要是对ZJoystick.h和ZJoystick.m的添加,实现了如下图的功能。通过摇杆可以控制图中精灵的移动。(但是还有一个技术性问题亟待解决,就是精灵移动后会有一个重影留在初始位置)
2.摇杆的实现
1) 将资源中的ZJoystick文件夹加到工程中(页面下方提供下载地址), 精灵的添加以及移动前面已经讲了,不知道的同学可以看教程四。工程名字为ControlWalking
。
2)修改HelloWorldLayer.h文件。加入一些需要的节点参数。 #import <GameKit/GameKit.h>
// When you import this file, you import all the cocos2d classes
#import "cocos2d.h"
#import "ZJoystick.h"
// HelloWorldLayer
@interface HelloWorldLayer : CCLayer<ZJoystickDelegate>
{
CCTexture2D *spriteTexture_; // weak ref
//b2World* world; // strong ref
//GLESDebugDraw *m_debugDraw; // strong ref
//CCTMXTiledMap *_gameMap;
CCSprite *_player;//是精灵,图中的熊猫
}
// returns a CCScene that contains the HelloWorldLayer as the only child
+(CCScene *) scene;
@end
#import <GameKit/GameKit.h>
// When you import this file, you import all the cocos2d classes
#import "cocos2d.h"
#import "ZJoystick.h"
// HelloWorldLayer
@interface HelloWorldLayer : CCLayer<ZJoystickDelegate>
{
CCTexture2D *spriteTexture_; // weak ref
//b2World* world; // strong ref
//GLESDebugDraw *m_debugDraw; // strong ref
//CCTMXTiledMap *_gameMap;
CCSprite *_player;//是精灵,图中的熊猫
}
// returns a CCScene that contains the HelloWorldLayer as the only child
+(CCScene *) scene;
@end
3) 修改HelloWorldLayer.m文件。
首先,在HelloWorld接口中定义摇杆函数
@interface HelloWorldLayer()
//-(void) initPhysics;
-(void) initJoystick;
@end
接着,添加initJoystick函数,方便在init中调用。
-(void) initJoystick{
ZJoystick *_joystick2 = [ZJoystick joystickNormalSpriteFile:@"JoystickContainer_norm.png"
selectedSpriteFile:@"JoystickContainer_trans.png"
controllerSpriteFile:@"Joystick_norm.png"];
_joystick2.position = ccp(_joystick2.contentSize.width/2 + 10,
_joystick2.contentSize.height/2 + 10);
_joystick2.delegate = self; //Joystick Delegate
_joystick2.controlledObject = _player;
_joystick2.speedRatio = 2.0f;
_joystick2.joystickRadius = 50.0f; //added in v1.2
_joystick2.joystickTag = 999;
[self addChild:_joystick2];
}
下一步,添加Joystick的一些属性,也直接写在HelloWorldLayer.m文件里。
#pragma mark - zJoystick delegate methods
-(void)joystickControlBegan {
// CCLOG(@"Joystick Began Controlling");
}
-(void)joystickControlMoved {
// CCLOG(@"Joystick Move Controlling");
}
-(void)joystickControlEnded {
// CCLOG(@"Joystick End Controlling");
}
-(void)joystickControlDidUpdate:(id)joystick toXSpeedRatio:(CGFloat)xSpeedRatio toYSpeedRatio:(CGFloat)ySpeedRatio{
ZJoystick *zJoystick = (ZJoystick *)joystick;
if (zJoystick.joystickTag == 999) {
CGFloat xPos = _player.position.x;
CGFloat yPos = _player.position.y;
_player.position = ccp(xPos + xSpeedRatio, yPos + ySpeedRatio);//定义精灵的移动方式
}
}
@end
最后一步就是要修改,init函数。前提是我们已经添加完成精灵(也就是图中的熊猫,前面第四章讲了)。
其实只要将精灵对象付给头文件中定义的_player,再调用一下前面定义的initJoystick就可以了。

本文介绍如何使用Cocos2d提供的摇杆控制器实现精灵的移动控制。通过添加ZJoystick组件并配置参数,可以创建一个功能性摇杆来控制游戏中的角色移动。

被折叠的 条评论
为什么被折叠?



