Движение спрайта с помощью джойстика? - PullRequest
0 голосов
/ 21 марта 2011

Как применить движение к спрайту с помощью джойстика в Cocos2d?

1 Ответ

2 голосов
/ 21 марта 2011

Все, что вам нужно сделать, - это уже сделать спрайт и SneakyJoyStick. Чтобы сделать SneakyJoyStick, просто Google Sneakyinput и нажмите на третью ссылку.

Как только вы это сделаете, и ваш проект будет открыт (дух ...), посмотрите на код ниже:

Вот HelloWorldLayer.h: (он может быть другим, только если это слой)

#import "cocos2d.h"

@ class SneakyJoystick;

@interface HelloWorldLayer : CCColorLayer {
    SneakyJoystick *leftJoyStick;
    CCSprite *character;
    CCNode *mainCharacter;
    CGPoint stickPosition;
    float degrees;
    CGPoint velocity;
    BOOL autoCenter;
    BOOL isDPad;
    BOOL hasDeadzone; //Turns Deadzone on/off for joystick, always YES if ifDpad == YES
    NSUInteger numberOfDirections; //Used only when isDpad == YES

    float joystickRadius;
    float thumbRadius;
    float deadRadius; //Size of deadzone in joystick (how far you must move before input starts). Automatically set if isDpad == YES

    //Optimizations (keep Squared values of all radii for faster calculations) (updated internally when changing joy/thumb radii)
    float joystickRadiusSq;
    float thumbRadiusSq;
    float deadRadiusSq;
}

@property (nonatomic, readonly) CGPoint stickPosition;
@property (nonatomic, readonly) CGPoint playerPosition;
@property (nonatomic, readonly) CGPoint playerPosition2;
@property (nonatomic, readonly) float degrees;
@property (nonatomic, readonly) CGPoint velocity;
@property (nonatomic, assign) BOOL autoCenter;
@property (nonatomic, assign) BOOL isDPad;
@property (nonatomic, assign) BOOL hasDeadzone;
@property (nonatomic, assign) NSUInteger numberOfDirections;

@property (nonatomic, assign) float joystickRadius;
@property (nonatomic, assign) float thumbRadius;
@property (nonatomic, assign) float deadRadius;

-(id)initWithRect:(CGRect)rect;

@end

А вот и HelloWorldLayer.m:

    // Import the interfaces
#import "HelloWorldLayer.h"
#import "SneakyJoystick.h"
#import "SneakyJoystickSkinnedBase.h"
#import "ColoredCircleSprite.h"

#define SJ_PI 3.14159265359f
#define SJ_PI_X_2 6.28318530718f
#define SJ_RAD2DEG 180.0f/SJ_PI
#define SJ_DEG2RAD SJ_PI/180.0f

@interface SneakyJoystick(hidden)
-(void)updateVelocity:(CGPoint)point;
-(void)setTouchRadius;
@end

// HelloWorldLayer implementation
@implementation HelloWorldLayer

@synthesize
stickPosition,
degrees,
velocity,
autoCenter,
isDPad,
hasDeadzone,
numberOfDirections,
joystickRadius,
thumbRadius,
deadRadius,
position,
playerPosition,
playerPosition2;

-(id)initWithRect:(CGRect)rect
{
    self = [super init];
    if(self){
        stickPosition = CGPointZero;
        playerPosition = ccp(150,150);
        degrees = 0.0f;
        velocity = CGPointZero;
        autoCenter = YES;
        isDPad = NO;
        hasDeadzone = NO;
        numberOfDirections = 4;

        self.joystickRadius = rect.size.width/2;
        self.thumbRadius = 32.0f;
        self.deadRadius = 0.0f;

        //Cocos node stuff
        position_ = rect.origin;
    }
    return self;
}

-(void)updateVelocity:(CGPoint)point
{
    // Calculate distance and angle from the center.
    float dx = point.x;
    float dy = point.y;
    float dSq = dx * dx + dy * dy;

    if(dSq <= deadRadiusSq){
        velocity = CGPointZero;
        degrees = 0.0f;
        stickPosition = point;
        return;
    }

    float angle = atan2f(dy, dx); // in radians
    if(angle < 0){
        angle       += SJ_PI_X_2;
    }
    float cosAngle;
    float sinAngle;

    cosAngle = cosf(angle);
    sinAngle = sinf(angle);

    // NOTE: Velocity goes from -1.0 to 1.0.
    if (dSq > joystickRadiusSq || isDPad) {
        dx = cosAngle * joystickRadius;
        dy = sinAngle * joystickRadius;
    }

    velocity = CGPointMake(dx/joystickRadius, dy/joystickRadius);
    degrees = angle * SJ_RAD2DEG;

    // Update the thumb's position
    stickPosition = ccp(dx, dy);
}

+(id) scene
{
    // 'scene' is an autorelease object.
    CCScene *scene = [CCScene node];

    // 'layer' is an autorelease object.
    HelloWorldLayer *layer = [HelloWorldLayer node];

    // add layer as a child to scene
    [scene addChild: layer];

    // return the scene
    return scene;
}

-(id) init
{
    // always call "super" init
    // Apple recommends to re-assign "self" with the "super" return value
    if( (self=[super initWithColor:ccc4(255,255,255,255)] )) {
        self.isTouchEnabled = YES;

        SneakyJoystickSkinnedBase *leftJoy = [[[SneakyJoystickSkinnedBase alloc] init] autorelease];
        leftJoy.position = ccp(72,72);
        leftJoy.backgroundSprite = [CCSprite spriteWithFile:@"dpad.png"];
        leftJoy.thumbSprite = [CCSprite spriteWithFile:@"joystick.png"];
        leftJoy.joystick = [[SneakyJoystick alloc] initWithRect:CGRectMake(0,0,128,128)];
        leftJoyStick = [leftJoy.joystick retain];
        [self addChild:leftJoy];

        character = [CCSprite spriteWithFile:@"player.jpg"];

        mainCharacter = character;
        [self addChild:mainCharacter];

        [self schedule:@selector(tick:)];

        [[CCDirector sharedDirector] setAnimationInterval:0.0000001f/10000.0f];

    }
    return self;
}

-(void)tick:(float)delta
{
    character.position = ccp(character.position.x + (leftJoyStick.velocity.x),
                             character.position.y + (leftJoyStick.velocity.y));

}

@end

Да, это как раз об этом!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...