将精灵移离Touch?的Cocos2D

时间:2011-02-21 20:06:59

标签: cocos2d-iphone

嘿大家, 我是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像素。因此,如果我触摸精灵的左侧,精灵向右移动,如果我触摸到顶部,精灵将向下移动......等等。

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

使用行动。在你的触摸开始方法中创建一个动作:

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];