我有一個精靈(一個球的圖像),我可以使用觸摸和移動來移動它。我還根據滑動週期確定了該精靈的位置(x軸,y軸)的變化率。ipad:如何通過滑動移動精靈,並根據滑動速度繼續前進
現在我需要繼續按照它的速度和方向繼續這個精靈。這裏是我的代碼 -
Touch Event
- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
CGPoint location = [touch locationInView: [touch view]];
CGPoint convertedLocation = [[CCDirector sharedDirector] convertToGL:location];
self.touchStartTime = [event timestamp];
self.touchStartPosition = location;
if (YES == [self isItTouched:self.striker touchedAt:convertedLocation]) {
self.striker.isInTouch = YES;
}
return YES;
}
- (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event {
CGPoint location = [touch locationInView: [touch view]];
CGPoint convertedLocation = [[CCDirector sharedDirector] convertToGL:location];
self.touchLastMovedTime = [event timestamp];
self.touchMovedPosition = convertedLocation;
if(self.striker.isInTouch == YES){
self.striker.position = self.touchMovedPosition;
}
}
- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event {
CGPoint location = [touch locationInView: [touch view]];
CGPoint convertedLocation = [[CCDirector sharedDirector] convertToGL:location];
self.touchEndTime = [event timestamp];
self.touchEndPosition = location;
if(self.striker.isInTouch == YES
&& (self.touchEndTime - self.touchLastMovedTime) <= MAX_TOUCH_HOLD_DURATION)
{
float c = sqrt(pow(self.touchStartPosition.x - self.touchEndPosition.x, 2)
+ pow(self.touchStartPosition.y - self.touchEndPosition.y, 2));
self.striker.speedx = (c - (self.touchStartPosition.y - self.touchEndPosition.y))
/((self.touchEndTime - self.touchStartTime) * 1000);
self.striker.speedy = (c - (self.touchStartPosition.x - self.touchEndPosition.x))
/((self.touchEndTime - self.touchStartTime) * 1000);
self.striker.speedx *= 4;
self.striker.speedy *= 4;
self.striker.isInTouch = NO;
[self schedule:@selector(nextFrame) interval:0.001];
}
}
Scheduled Method to move Sprite
- (void) nextFrame {
[self setPieceNextPosition:self.striker];
[self adjustPieceSpeed:self.striker];
if(abs(self.striker.speedx) <= 1 && abs(self.striker.speedy) <= 1){
[self unschedule:@selector(nextFrame)];
}
}
SET next Position
- (void) setPieceNextPosition:(Piece *) piece{
CGPoint nextPosition;
float tempMod;
tempMod = (piece.position.x + piece.speedx)/SCREEN_WIDTH;
tempMod = (tempMod - (int)tempMod)*SCREEN_WIDTH;
nextPosition.x = tempMod;
tempMod = (piece.position.y + piece.speedy)/SCREEN_HEIGHT;
tempMod = (tempMod - (int)tempMod)*SCREEN_HEIGHT;
nextPosition.y = tempMod;
piece.position = nextPosition;
}
Set new Speed
- (void) adjustPieceSpeed:(Piece *) piece{
piece.speedx =(piece.speedx>0)? piece.speedx-0.05:piece.speedx+0.05;
piece.speedy =(piece.speedy>0)? piece.speedy-0.05:piece.speedy+0.05;
}
雖然,目前我使用靜態速度調整技術,但我希望讓它動視初始速度(我明白任何想法)
爲進一步信息,請讓我知道 – Sadat 2010-07-13 08:46:54