I am writing a game using the Cocos2d library for iOS. So far I have a sprite on the screen that I would like to drag around. Basically I have a CGPoint called End. When I drag across the screen it moves. I want to have the sprite figure out on each frame whether End has moved, and if it has start moving toward it at a given velocity, and stop right on top of it. End is like an anchor. I have accomplished the first two steps by plotting out the vector like this:
-(void) update:(ccTime)deltaTime
{
CGPoint Pos = _player.position;
velocity = 15;
diff.x = End.x - _player.position.x;
diff.y = End.y - _player.position.y;
length = ccpLength(diff);
norm.x = diff.x / length * velocity;
norm.y = diff.y / length * velocity;
Pos.x += norm.x;
Pos.y += norm.y;
}
I move the End point around like this:
- (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)even开发者_运维技巧t
{
CGPoint touchLocation = [self convertTouchToNodeSpace:touch];
CGPoint oldTouchLocation = [touch previousLocationInView:touch.view];
oldTouchLocation = [[CCDirector sharedDirector sharedDirector] convertToGL:oldTouchLocation];
oldTouchLocation = [self convertToNodespace:oldTouchLocation];
CGPoint diff = ccpSub(touchLocation, oldTouchLocation);
End = ccpAdd(End, diff);
}
What is the best way to detect when the _player has reached it's destination? I've tried this a number of ways, but I really can't get it to be precise enough. I tried adding a timer that times the duration of each move, so I could test if velocity * duration >= length. Is that the way to do it? It didn't work out too well. Any master programmers want to give me some tips?
At the end of your update method, check for distance. If distance is under velocity, you're done, set the position to the endpoint and fire off whatever method you'd like. In cocos2d, you can use the method ccpDistance
.
精彩评论