Вращающийся спрайт с пальцем в Cocos2d - PullRequest
3 голосов
/ 15 марта 2011

Мне нужна помощь в определении вращения спрайта с помощью моего пальца. Спрайт вращается нормально, но при первом касании моего пальца он как-то поворачивается на несколько градусов сам по себе.

Также вращения работают только тогда, когда палец вращается вокруг центра спрайта.

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

Вот полный код

#import "BicycleScene.h"

@implementation BicycleScene

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

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

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

    // return the scene
    return scene;
}

-(id) init
{
    if ((self=[super init])) {

        CGSize winSize = [[CCDirector sharedDirector] winSize];

        //place the bicycle sprite
        bicycleSprite = [CCSprite spriteWithFile:@"bike_gear.png"];
        bicycleSprite.position = ccp(bicycleSprite.contentSize.width/2 + 100, winSize.height/2);
        [self addChild:bicycleSprite z:1];

        //place the pedal sprite
        pedalSprite = [CCSprite spriteWithFile:@"bike_pedal.png"];
        [bicycleSprite addChild:pedalSprite z:1];

        pedalSprite.position = ccp(150, 15);

        //enable touch
        self.isTouchEnabled = YES;

        [self schedule:@selector(gameLoop:) interval:.1/100];

    }

    return self;
}

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

    NSLog(@"Touch begun");

}

-(void)gameLoop:(ccTime) dt{

    bicycleSprite.rotation = cocosAngle;
}

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

    NSLog(@"Touch moved");

    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:[touch view]];
    CGPoint previousLocation = [touch previousLocationInView:[touch view]];

    CGPoint touchingPoint = [[CCDirector sharedDirector] convertToGL:location];
    CGPoint previousTouchingPoint = [[CCDirector sharedDirector] convertToGL:previousLocation];

    CGPoint vector = ccpSub(touchingPoint, bicycleSprite.position);
    CGFloat rotateAngle = -ccpToAngle(vector);

    previousAngle = cocosAngle;
    cocosAngle = CC_RADIANS_TO_DEGREES( rotateAngle);

    //bicycleSprite.rotation = cocosAngle;
}

@end

Я немного запутался, если строка:

CGPoint vector = ccpSub(touchingPoint, bicycleSprite.position);

на самом деле должно быть:

CGPoint vector = ccpSub(touchingPoint, previousTouchingPoint );

Я тоже это пробовал, но это не сработало.

Я также загрузил свой полный xcodeproj в 4shared для всех, кто хочет посмотреть здесь: http://www.4shared.com/file/5BaeW4oe/Healthy.html

Ответы [ 2 ]

9 голосов
/ 21 марта 2011
@interface MainScene : CCLayer {
    CCSprite *dial;

    CGFloat dialRotation;

}

+ (id)scene;

@end
---------------------------------
@implementation MainScene

+ (id)scene
{
    CCScene *scene = [CCScene node];
    CCLayer *layer = [MainScene node];
    [scene addChild:layer];

    return scene;
}

- (id)init
{
    if((self = [super init])) {
        CCLOG(@"MainScene init");

        CGSize size = [[CCDirector sharedDirector]winSize];

        dial = [CCSprite spriteWithFile:@"dial.png"];
        dial.position = ccp(size.width/2,dial.contentSize.height/2);
             [self addChild:dial];

        self.isTouchEnabled = YES;
        [self scheduleUpdate];

    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
}

- (void)update:(ccTime)delta
{
    dial.rotation = dialRotation;
}

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

}

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

    //acquire the previous touch location
    CGPoint firstLocation = [touch previousLocationInView:[touch view]];
    CGPoint location = [touch locationInView:[touch view]];

    //preform all the same basic rig on both the current touch and previous touch
    CGPoint touchingPoint = [[CCDirector sharedDirector] convertToGL:location];
    CGPoint firstTouchingPoint = [[CCDirector sharedDirector] convertToGL:firstLocation];

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

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

    //keep adding the difference of the two angles to the dial rotation
    dialRotation += currentTouch - previousTouch;
}

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

}

РЕДАКТИРОВАТЬ: Извините, я не могу заставить это остаться в режиме кода.Но это решение, и оно должно быть легко реализовано в вашем коде.ура! * * 1002

0 голосов
/ 18 марта 2011

В ccTouchesBegan используйте тот же код, что и в ccTouchesMoved, чтобы определить угол, затем перейдите к этому углу, используя CCRotateTo. Вам понадобится немного позаботиться о том, чтобы пользователь двигал пальцем, пока CCRotateTo активен, возможно, останавливая текущее действие и отбрасывая другое, чтобы перейти к новому углу.

...