Вращение Cocos2d на ощупь переместило проблему - PullRequest
0 голосов
/ 30 июня 2011

У меня есть копье как спрайт. Его вращение определяется методом touchesMoved. всякий раз, когда пользователь скользит пальцем, он указывает на это прикосновение. Это мой метод:

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

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


    float angleRadians = atanf((float)location.y / (float)location.x);
    float angleDegrees = CC_RADIANS_TO_DEGREES(angleRadians);

    spear.rotation = -1 * angleDegrees;

}

Это вроде работает, но только от 0 до 45 градусов. и это идет наоборот. Так как я двигаюсь от пальца снизу вверх, он вращается по часовой стрелке (он должен следовать направлению фингера и вращаться против часовой стрелки). С 45 по 90 он работает нормально (движется против часовой стрелки), но только если я запускаю касание в верхней диагонали экрана.

Что я делаю не так? Спасибо

Ответы [ 3 ]

1 голос
/ 30 июня 2011
#define PTM_RATIO 32

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

    for( UITouch *touch in touches ) {

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

        location = [[CCDirector sharedDirector] convertToGL: location];

        b2Vec2 locationWorld = b2Vec2(location.x/PTM_RATIO, location.y/PTM_RATIO);

        spriteBody->SetTransform(locationWorld,spriteBody->GetAngle());
    }
}

-(void) tick: (ccTime) dt
{

    //It is recommended that a fixed time step is used with Box2D for stability
    //of the simulation, however, we are using a variable time step here.
    //You need to make an informed choice, the following URL is useful
    //http://gafferongames.com/game-physics/fix-your-timestep/

    int32 velocityIterations = 8;
    int32 positionIterations = 1;

    // Instruct the world to perform a single step of simulation. It is
    // generally best to keep the time step and iterations fixed.
    m_world->Step(dt, velocityIterations, positionIterations);

    //  for (int i = 0; i < (int)birds.size(); i++)
    //      birds[i]->render();

    //Iterate over the bodies in the physics world
    for (b2Body* b = m_world->GetBodyList(); b; b = b->GetNext())
    {
        if (b->GetUserData() != NULL) {
            //Synchronize the AtlasSprites position and rotation with the corresponding body
            CCSprite *myActor = (CCSprite*)b->GetUserData();
            myActor.position = CGPointMake( b->GetPosition().x * PTM_RATIO, b->GetPosition().y * PTM_RATIO);
            myActor.rotation = -1 * CC_RADIANS_TO_DEGREES(b->GetAngle());
        }   
    }
}
0 голосов
/ 01 июля 2011
CGPoint touchLocation = [touch locationInView: [touch view]];
touchLocation = [[CCDirector sharedDirector] convertToGL:touchLocation];
touchLocation = [self convertToNodeSpace:touchLocation];    
GPoint diff = ccpSub(touchLocation, _player.position);

//rotate to face the touch
CGPoint diff = ccpSub(_player.position, touchLocation);
float angleRadians = atanf((float)diff.y / (float)diff.x);
float angleDegrees = CC_RADIANS_TO_DEGREES(angleRadians);
float cocosAngle = -1 * angleDegrees;

if(diff.x < 0)
{
            cocosAngle += 180;
}

id actionRotateTo = [CCRotateTo actionWithDuration:0.1 angle:cocosAngle];
[_player runAction:actionRotateTo];
0 голосов
/ 01 июля 2011

Разобрался, что было не так. Мне нужно было изменить CGPoint, который я получил от прикосновений, на точку GL следующим образом:

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

location = [[CCDirector sharedDirector] convertToGL: location];

Глупый я. Должен был подумать об этом раньше.

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