实施例: 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像素。因此,如果我触摸精灵的左侧,精灵向右移动,如果我触摸到顶部,精灵将向下移动......等等。
感谢您的帮助!
答案 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];