iPhone游戏中模拟摇杆的教程

来源:互联网 发布:希尔瓦娜斯手办淘宝 编辑:程序博客网 时间:2024/05/01 16:56
很多比较激烈,操作频率很高的游戏中,使用加速度感应往往不如用模拟摇杆操作。今天带来CocoaChina会员 “qwertyuasdf”的原创教程:模拟摇杆的简单实现。
作者博客原文:http://blog.team-cusr.com/?p=152 论坛讨论帖地址  http://www.cocoachina.com/bbs/read.php?tid-16365.html

实现功能:

初始化:模拟摇杆自定位,自定范围(半径),自定图片.

控制:摇杆开关

输出:摇杆方向,摇杆 速度

\效果
直接上代码了,直接看注释吧
joystick.h:
 
#import "cocos2d.h"
 
@interface joystick : CCLayer {//继承于cocos的层
CGPoint centerPoint;//摇杆中心
CGPoint currentPoint;//摇杆当前位置
BOOL active;//是否激活摇杆
float radius;//摇杆半径
CCSprite *jsSprite;
}
//初始化 aPoint是摇杆中心 aRadius是摇杆半径 aJsSprite是摇杆控制点 aJsBg是摇杆背景
+ (id) initWithCenter:(CGPoint)aPoint Radius:(float)aRadius jsPic:(CCSprite*)aJsSprite jsBg:(CCSprite*)aJsBg;
- (id) initWithCenter:(CGPoint)aPoint Radius:(float)aRadius jsPic:(CCSprite*)aJsSprite jsBg:(CCSprite*)aJsBg;
 
- (void) Active;
- (void) Inactive;
- (CGPoint) getDirection;
- (float) getVelocity;
- (void) updatePos:(ccTime) dt;//控制点位置刷新
 
@end

joystick.m
#import "joystick.h"
 
@implementation joystick
//初始化
+ (id) initWithCenter:(CGPoint)aPoint Radius:(float)aRadius jsPic:(CCSprite *)aJsSprite jsBg:(CCSprite *)aJsBg{
return [[[self alloc] initWithCenter:aPoint Radius:aRadius jsPic:aJsSprite jsBg:aJsBg] autorelease];
}
 
- (id) initWithCenter:(CGPoint)aPoint Radius:(float)aRadius jsPic:(CCSprite*)aJsSprite jsBg:(CCSprite*)aJsBg;
{
if ( (self=[super init]) ) {
active = NO;
radius = aRadius;
centerPoint = aPoint;
currentPoint = centerPoint;
jsSprite = aJsSprite;
jsSprite.position=centerPoint;
aJsBg.position=centerPoint;

[self addChild:jsSprite];
[self addChild:aJsBg];
}
return self;
}
 
- (void) updatePos:(ccTime)dt{
jsSprite.position = ccpAdd(jsSprite.position,ccpMult(ccpSub(currentPoint, jsSprite.position),0.5));
}
//激活摇杆
- (void) Active
{
if (!active) {
active=YES;
[self schedule:@selector(updatePos:)];//添加刷新函数

[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:INT_MIN+1 swallowsTouches:NO];//添加触摸委托
}else {
NSLog(@"JoyStick is already active.");
}
}
//冻结摇杆
- (void) Inactive
{
if (active) {
active=NO;

[self unschedule:@selector(updatePos:)];//删除刷新
[[CCTouchDispatcher sharedDispatcher] removeDelegate:self];//删除委托
}else {
NSLog(@"JoyStick is already inactive.");
}
}
//3个触摸函数
- (BOOL) ccTouchBegan:(UITouch*)touch withEvent:(UIEvent*)event
{
if (!active) return NO;
CGPoint touchPoint = [touch locationInView:[touch view]];
touchPoint = [[CCDirector sharedDirector] convertToGL:touchPoint];
if (ccpDistance(touchPoint, centerPoint) > radius) return NO;

currentPoint = touchPoint;
return YES;
}
 
- (void) ccTouchMoved:(UITouch*)touch withEvent:(UIEvent*)event
{
CGPoint touchPoint = [touch locationInView:[touch view]];
touchPoint = [[CCDirector sharedDirector] convertToGL:touchPoint];
if (ccpDistance(touchPoint, centerPoint) > radius)
{
currentPoint =ccpAdd(centerPoint,ccpMult(ccpNormalize(ccpSub(touchPoint, centerPoint)), radius));
}else {
currentPoint = touchPoint;
}
1 0