Home:ALL Converter>Accelerometer and Sprite Face Direction

Accelerometer and Sprite Face Direction

Ask Time:2014-06-19T03:03:28         Author:john doe

Json Formatter

I am making a simple game where my sprite is moved through the use of accelerometer. My sprite is a circle with eyes on it. I want to rotate the sprite in a way that it is always facing towards the direction it is moving. The below code successfully moves the sprite using the accelerometer but I am having trouble rotating the sprite to face the direction of the movement.

-(void) moveHeroFromAccelaration
{
    GLKVector3 raw = GLKVector3Make(_motionManager.accelerometerData.acceleration.x,_motionManager.accelerometerData.acceleration.y,_motionManager.accelerometerData.acceleration.z);

    if(GLKVector3AllEqualToScalar(raw, 0))
        return;

    static GLKVector3 ax, ay, az;
    ay = GLKVector3Make(0.63f, 0.0f, -0.92f);
    az = GLKVector3Make(0.0f, 1.0f, 0.0f);
    ax = GLKVector3Normalize(GLKVector3CrossProduct(az, ay));

    CGPoint accel2D = CGPointZero;
    accel2D.x = GLKVector3DotProduct(raw, az); accel2D.y = GLKVector3DotProduct(raw, ax);
    accel2D = CGPointNormalize(accel2D);

    static const float steerDeadZone = 0.18;
    if (fabsf(accel2D.x) < steerDeadZone) accel2D.x = 0; if (fabsf(accel2D.y) < steerDeadZone) accel2D.y = 0;

    float maxAccelerationPerSecond = 160.0f;
    _hero.physicsBody.velocity =
    CGVectorMake(accel2D.x * maxAccelerationPerSecond, accel2D.y * maxAccelerationPerSecond);

    //1
    if (accel2D.x!=0 || accel2D.y!=0) {
        //2
        float orientationFromVelocity = CGPointToAngle(CGPointMake(_hero.physicsBody.velocity.dx,
                                                                   _hero.physicsBody.velocity.dy));

        float angleDelta = 0.0f;
        //3
        if (fabsf(orientationFromVelocity-_hero.zRotation)>1) { //prevent wild rotation
            angleDelta = (orientationFromVelocity-_hero.zRotation);
        } else {
            //blend rotation
            const float blendFactor = 0.25f; angleDelta =
            (orientationFromVelocity - _hero.zRotation) * blendFactor; angleDelta =
            ScalarShortestAngleBetween(_hero.zRotation, _hero.zRotation + angleDelta);
        }
        _hero.zRotation += angleDelta;


        // face the hero in the moving direction 
        [_hero runAction:[SKAction rotateToAngle:orientationFromVelocity duration:0.25 shortestUnitArc:YES]]; <---- THIS IS WHERE I NEED HELP! 

    }

}

Author:john doe,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/24293220/accelerometer-and-sprite-face-direction
yy