【问题标题】:Move sprite away from Touch? Cocos2d将精灵从 Touch 上移开? Cocos2d
【发布时间】:2011-02-21 20:06:59
【问题描述】:

大家好, 我是 cocos2d 和 Objective-C 的新手,所以如果有一个简单的解决方案,我深表歉意。 我正在为我正在开发的游戏编写一些代码。在这个游戏中,我在屏幕上有一个精灵,我希望这个精灵在触摸位置的对面移动。

示例: Picture Example

到目前为止,我的代码如下所示:

-(void) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
//Determine location of the tap/touch
CGPoint touchLocation = [touch locationInView: [touch view]];
touchLocation = [[CCDirector sharedDirector] convertToGL: touchLocation];
touchLocation = [self convertToNodeSpace:touchLocation];

我在 init 方法中将我的精灵添加到场景中,如下所示:

        CGSize screenSize = [[CCDirector sharedDirector] winSize];

    Ball* ball = [Ball ball];
    ball.position = CGPointMake(ball.contentSize.width / 2, screenSize.height / 2);
    [self addChild:ball z:2];

我希望这样,无论我在屏幕上触摸什么位置,精灵都会在触摸位置的对面移动 20 像素。所以如果我触摸精灵的左侧,精灵就会向右移动,如果我触摸到顶部,精灵就会向下移动..等等。

感谢您的帮助!

【问题讨论】:

    标签: cocos2d-iphone


    【解决方案1】:

    使用动作。在你的 touch started 方法中创建一个动作:

    CGPoint vector;
    vector.x = ball.position.x - touchLocation.x;
    vector.y = ball.position.y - touchLocation.y;
    
    float vectorLength = sqrt(vector.x*vector.x + vector.y*vector.y);
    if (fabs(vectorLength) < 0.1) return; //tapped directly to the center of sprite
    
    vector.x *= 20 / vectorLength;
    vector.y *= 20 / vectorLength;
    
    id action = [CCMoveBy actionWithDuration: 0.5 position: vector];
    [ball runAction: action];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多