Search code examples
iphoneobjective-ccocos2d-iphoneccsprite

Moving a sprite with touches began, casting and parameters in obj - c?


I've been reading a book on the cocos2d framework for ios5 for a few days and have developed a small game that the book walks you through. To control the sprite in this game you use the accelerometer:

-(void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{

    float deceleration = 0.4f;
    float sensitivity = 6.0f;
    float maxVelocity = 100;

    // adjust velocity based on current accelerometer acceleration
    playerVelocity.x = playerVelocity.x * deceleration + acceleration.x * sensitivity;

    // we must limit the maximum velocity of the player sprite, in both directions (positive & negative values)
    if (playerVelocity.x > maxVelocity)
    {
        playerVelocity.x = maxVelocity;
    }
    else if (playerVelocity.x < -maxVelocity)
    {
        playerVelocity.x = -maxVelocity;
    }

    // Alternatively, the above if/else if block can be rewritten using fminf and fmaxf more neatly like so:
    // playerVelocity.x = fmaxf(fminf(playerVelocity.x, maxVelocity), -maxVelocity);
}

Now I'm wondering if I can change this code to allow the sprite to still accelerate/decelerate along the x axis, but to use touch input rather than the accelerometer, and to go faster the longer the touch is held down for? So a touch to the right would move the sprite to that spot slowly, if the touch is released, it stops moving to that spot. The longer a touch is held down, the faster the sprite moves.

is there anything in the framework to allow me to implement a rotation mechanism that allows my sprite to rotate to the position that the touch was in, so it looks like its facing the point thats been touched?


Solution

  • Well, afaik theres no method that will determine the angle to the touch and then rotate the sprite accordingly, but if you have the x and y coordinates of the sprite and the touch you can calculate it yourself fairly easily.

    CGPoint spriteCenter; // this should represent the center position of the sprite
    CGPoint touchPoint; //location of touch
    
    float distanceX = touchPoint.x - spriteCenter.x;
    float distanceY = touchPoint.y - spriteCenter.y;
    
    float angle = atan2f(distanceY,distanceX); // returns angle in radians
    
    // do whatever you need to with the angle
    

    Once you have the angle you can set the rotation of the sprite.