在我的游戏中,我需要计算触摸的持续时间。我是这样做的:
-(BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
self.endTime = [NSDate date]; //NSDate *endTime in .h
NSLog(@"%@",self.endTime);
}
-(void) ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event
{
tStart = [[NSDate date] timeIntervalSinceDate:self.endTime];
NSLog(@"duration %f",tStart);
我使用此时间间隔作为计算玩家跳跃高度的因素。 较少的是tStart,低的是跳跃,更多是tStart,高是跳跃。我这样做:
if(tStart/1000<=9.430)
{
[player jump:5.0f];
}
else if(tStart>9.430 && tStart<=9.470)
{
[player jump:7.0f];
}
else if(tStart/1000>9.470)
{
[player jump:8.0f];
}
但是我想在tochBegan上执行此操作,以便玩家可以在触摸屏幕时立即跳转。为此需要touchBegan中tStart的值。我该怎么办?
由于
答案 0 :(得分:1)
对于给定的触摸,UITouch实例是相同的,因此在ccTouchBegan中使用最旧的时间戳保存触摸/触摸,然后等待ccTouchEnded。当你得到之前保存的UITouch时,就意味着玩家抬起了手指。
<强>更新强>
你可以
选项4不实用,因为用户可以根据需要继续按下。因此,假设您想要进行变量跳转,这里是选项3的代码:
UITouch *jump = nil;
-(BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
// no jump ongoing, start one
if (jump==nil){
jump = touch;
// jump on a separate thread
[NSThread performSelectorInBackground:(SEL)jump withObject:touch];
}
}
-(void) jump:(UITouch*) touch {
NSInterval time = [touch timestamp]; // I *think* this is the time since system uptime :P
int jumpSpeed = 1;
// increase the jump speed for every 100ms up to 'maxTimeYouAreAllowedToJump' ms
while ( ([NSProcessInfo systemUptime]-time < maxTimeYouAreAllowedToJump) && (jump!=nil) ){
jumpSpeed += 1;
[NSThread sleepForTimeInterval:.1]; // sleep for 100ms
}
[self doTheJumpingWithSpeed:jumpSpeed]; // do the actual jump!
}
-(void) ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event {
// user released the touch that initiated the jump
if ((touch!=nil) && (touch==jump)) {
jump =nil;
}
}