目标c - 在较大的圆圈内移动小圆圈

时间:2014-08-20 13:49:12

标签: ios objective-c cocos2d-iphone

我试图在较大的圆圈内移动一个较小的圆圈,并将较小的圆圈保持在较大圆圈的圆周范围内。

这是我到目前为止所做的:

-(void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event{
    if (isJoystickToggle) {

        if(CGRectContainsPoint(joystickContainer.boundingBox, [self convertTouchToNodeSpaceAR:touch])){

            float posY = joystickContainer.position.y;
            float posX = joystickContainer.position.x;
            float y = joystickToggle.position.y;
            float x = joystickToggle.position.x;
            float angle = atan2f( y - posY , x - posX);

            double dx = (x-posX);
            double dy = (y-posY);
            double dist = sqrt(dx*dx + dy*dy);

            NSLog(@"%f",dist);


            if (dist < 60) {

                CGPoint location = [touch locationInView: [touch view]];
                location = [[CCDirector sharedDirector] convertToGL:location];

                joystickToggle.position = location;
            }

        }

    }
}

较大的圆高和宽度为120,较小的圆宽和高度为36。

更新

-(BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event{

            if(CGRectContainsPoint(joystickToggle.boundingBox, [self convertTouchToNodeSpaceAR:touch])){
            isJoystickToggle = true;
            }

            return true;

        }

        -(void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event{
            if (isJoystickToggle) {

            joystickToggle.position = ccp(64, 64);

            }
        }

1 个答案:

答案 0 :(得分:0)

Larme谢谢你,大圈内的小圆圈现在正在运作:

-(void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event{
        if (isJoystickToggle) {


        CGPoint location = [touch locationInView: [touch view]];
        location = [[CCDirector sharedDirector] convertToGL:location];

        float posY = joystickContainer.position.y;
        float posX = joystickContainer.position.x;
        float y = location.y;
        float x = location.x;

        double dx = (x-posX);
        double dy = (y-posY);
        double dist = sqrt(dx*dx + dy*dy);

        NSLog(@"%f",dist);

        if (dist < 60) {

            joystickToggle.position = location;

        }

        if(dist >= 60){
            float angle = atan2f( y - posY , x - posX);

            float newx = (cos(angle) * 60) + posX;
            float newy = (sin(angle) * 60) + posY;

            location = ccp(newx, newy);
            joystickToggle.position = location;

        }

        }
    }