views:

26

answers:

1

How can I rotate sprite around his center in cocos2d in ccTouchesMoved. I found some code, but this not what I need. I need to rotate sprite like photo in Photo gallery app.


- (void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    NSArray *allTouch = [touches allObjects];
    if([allTouch count] > 1){
        UITouch *touch = [allTouch objectAtIndex:0];
        CGPoint point = [touch locationInView: [touch view]];
        point = [[CCDirector sharedDirector] convertToGL:point];

        float angleRadians = atanf((float)point.y / (float)point.x);
        float angleDegrees = CC_RADIANS_TO_DEGREES(angleRadians);
        float cocosAngle = -1 * angleDegrees;
        imageFromPicker.rotation = imageFromPicker.rotation + cocosAngle;

    }
}
+1  A: 

probably is not the best way but im using this:

When I touch the sprite with two fingers, i use the arctan of the two points to rotate the sprite:

first i look for the direction with this function:

static inline int ccw(CGPoint p0, CGPoint p1, CGPoint p2)
{
    int dx1, dx2, dy1, dy2;

    dx1 = p1.x - p0.x; dy1 = p1.y - p0.y;
    dx2 = p2.x - p0.x; dy2 = p2.y - p0.y;

    int v1 = dx1 * dy2;
    int v2 = dy1 * dx2;

    if (v1 > v2)
        return 1;

    if (v1 < v2)
        return -1;

    if ((dx1*dx2 < 0) || (dy1*dy2 < 0))
        return -1;

    if ((dx1*dx1 + dy1*dy1) < (dx2*dx2 + dy2*dy2))
        return 1;

    return 0;
}

and after on the ccTouchesMoved method I do this:

if ([allTouches count] == 2) {
            rotating=TRUE;
            NSArray *twoTouches = [allTouches allObjects];
            UITouch *first = [twoTouches objectAtIndex:0];
            UITouch *second = [twoTouches objectAtIndex:1];

            CGPoint a = [first previousLocationInView:[touch view]];
            CGPoint b = [second previousLocationInView:[touch view]];
            CGPoint c = [first locationInView:[touch view]];



            int direction =ccw(b, a, c);
            float pX= fabs(c.x-b.x);
            float pY= fabs(c.y-b.y);

            float rotation  = atan2(pY, pX);
        //  rotTotal= (rotTotal+rotacion)/10;
            if(direction<0)
            YourSprite.rotation=(YourSprite.rotation-rotation);
            else
            YourSprite.rotation=(YourSprite.rotation+rotation);

             }

it works for me, hope it works for you too

JonLOo
if you want to rotate more smoothly, you can add a coeficient here float rotation = atan2(pY, pX)*coef;
JonLOo
It works :) I have added a coefficient and its looks very good. I also added scalling method and it remains to add the mask, and then save the sprite. Thank you!
BUDDAx2
you are welcome :)
JonLOo