Определить, вращается ли спрайт на 360 градусов - Cocos2d - PullRequest
0 голосов
/ 06 мая 2011

У меня есть спрайт, который вращается с прикосновением. Я должен быть в состоянии определить, повернулся ли он на 360 градусов 3 раза. Есть ли способ сказать?

Вот что у меня есть

#import <Foundation/Foundation.h>
#import "cocos2d.h"
#import "GameScene.h"



@interface G : CCLayer {

    CCSprite *g;

    CGFloat gRotation;
}

@end

------------------------------------------
#import "G.h"


@implementation G

-(id) init
{
    if ((self = [super init]))
    {
        CCLOG(@"%@: %@", NSStringFromSelector(_cmd), self);

        g = [CCSprite spriteWithFile:@"g.png"];

        [self addChild:g z:-1];
    }
    return self;
}

- (void)update:(ccTime)delta
{
    g.rotation = gRotation;
}

- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{

}

- (void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];

    CGPoint firstLocation = [touch previousLocationInView:[touch view]];
    CGPoint location = [touch locationInView:[touch view]];

    CGPoint touchingPoint = [[CCDirector sharedDirector] convertToGL:location];
    CGPoint firstTouchingPoint = [[CCDirector sharedDirector] convertToGL:firstLocation];

    CGPoint firstVector = ccpSub(firstTouchingPoint, g.position);
    CGFloat firstRotateAngle = -ccpToAngle(firstVector);
    CGFloat previousTouch = CC_RADIANS_TO_DEGREES(firstRotateAngle);

    CGPoint vector = ccpSub(touchingPoint, g.position);
    CGFloat rotateAngle = -ccpToAngle(vector);
    CGFloat currentTouch = CC_RADIANS_TO_DEGREES(rotateAngle);

    gRotation += currentTouch - previousTouch;
}

- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{

}

- (void) dealloc
{
    CCLOG(@"%@: %@", NSStringFromSelector(_cmd), self);

    [super dealloc];
}

@end

GameScene

#import "GameScene.h"
#import "MainMenu.h"
#import "G.h"


@implementation GameScene

+(CCScene *) scene
{
    CCScene *scene = [CCScene node];
    GameScene *layer = [GameScene node];

    [scene addChild: layer];
    return scene;
}

-(void) tapG: (id) sender
{

    G *gView;
    gView = [[G alloc] init];
    gView.position = ccp(100, 100);

    [self.parent addChild:gView z:1001];

    [gView scheduleUpdate];

    [gView release];
}
-(id) init
{
    if ((self = [super init]))
    {
tG = [CCMenuItemImage itemFromNormalImage:@"tp.png" selectedImage:@"tp.png"  disabledImage:@"tpaperd.png" target:self selector:@selector(tapG:)];

        gt = [CCMenu menuWithItems:tG, nil];
        gt.position = ccp(210, 80);
        [gt alignItemsHorizontallyWithPadding:10];

        [self addChild:gt z:0];

    }
    return self;
}
- (void) dealloc
    {
        CCLOG(@"%@: %@", NSStringFromSelector(_cmd), self);

        [super dealloc];
    }

Кто-нибудь может помочь? Заранее спасибо

1 Ответ

2 голосов
/ 06 мая 2011

cocos2d может вращаться более чем на 360. но если вы идете влево и вправо, то это немного сложнее, чем просто проверка, если sprite.rotation == 1080.если вращение происходит по вашему touchesMoved методу, то вам следует записать максимальное вращение (возможно, вращение вправо) и самое низкое вращение (наоборот), и тогда разница должна быть больше 360 * 3.так что добавьте 2 класса в ваш слой G float maxRot,minRot;

- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    maxRot = mySprite.rotation; // here you set the ivars to defaults. 
    minRot = mySprite.rotation; // im setting them to your sprite initial rotation
}                               // incase it is not 0

в конце вашего touchesMoved метода, который вы проверите для своих условий:

if (mySprite.rotation > maxRot)
   maxRot = mySprite.rotation;

else if (mysprite.rotation < minRot)
   minRot = mySprite.rotation;

if ((maxRot - minRot) >= (360*3)) {

    // your condition is satisfied
}

я не проверял это такэто может быть просто неправильно ... но это стоит попробовать

РЕДАКТИРОВАТЬ:

приведенный выше код не будет работать, если вращения не происходят в одном направлении ... он не будет работать для вас,левое, правильное состояние.Я предполагаю, что один из способов - отслеживать направление вашего вращения в touchesMoved.так что опять вам понадобится класс vars

int numOfRots;
float previousRot, currentRot, accumRot;
BOOL isPositive, isPreviousPositive;

ваши методы касания:

- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    previousRot = mySprite.rotation; 
    currentRot = mySprite.rotation;
    accumRot = 0;
    numOfRots = 0;
    isPositive = NO;
    isPreviousPositive = NO;
}

в конце touchesMoved у вас будет следующее:

currentRot = mySprite.rotation;

if (currentRot > previousRot)
    isPositive = YES;
else
    isPositive = NO;

if (isPositive != isPreviousPositive) {

    // now we have a change in direction, reset the vars
    accumRot = 0;
}

if (isPositive) {

   accumRot += abs(currentRot - previousRot);
}

else {

   accumRot += abs(previousRot - currentRot); 
}


if (accumRot >= 360) {

    //now we have one rotation in any direction.
    numOfRots++;        
    //need to reset accumRot to check for another rot
    accumRot = 0;


    if (numOfRots == 3) {

        //BINGO!!! now you have 3 full rotations
    }
}

previousRot = currentRot;
isPreviousPositive = isPositive;

надеюсь, это поможет

...