触摸速度随场景中物体的数量而变化



我正在创建一款游戏,用户可以用球拍击中从屏幕顶部落下的物体。用户可以连续移动球拍,但如果它处于最低速度或静止状态,它不应该击中物体,但如果它高于最低速度,用户应该击中它们。我已经实现了这一点,但问题是当用户开始触摸球拍时,球拍随着用户的触摸不断移动,速度变化是他们的,它不是以相同的速度开始的,而触摸在那个时候移动,有时速度也非常少,即使运动很快。这是我的代码

-(void)didMoveToView:(SKView *)view {
self.physicsWorld.contactDelegate = (id)self;
racketNode = [SKSpriteNode spriteNodeWithImageNamed:@"racket"];
racketNode.size = CGSizeMake(50,50);
racketNode.position = CGPointMake(self.frame.origin.x + self.frame.size.width - 50,50);
racketNode.name = @"racket";
[self addChild:racketNode];
}
-(void) didBeginContact:(SKPhysicsContact *)contact {
SKSpriteNode *nodeA = (SKSpriteNode *)contact.bodyA.node ;
SKSpriteNode *nodeB = (SKSpriteNode *) contact.bodyB.node;
if (([nodeA.name isEqualToString:@"racket"] && [nodeB.name isEqualToString:@"fallingObject"])) {
    if (racketNode.speed > kMinSpeed)
        [nodeB removeFromParent];
    else {
        nodeB.physicsBody.contactTestBitMask = 0;
        [self performSelector:@selector(providingCollsion:) withObject:nodeB afterDelay:0.1];
    }
 }
}
-(void) providingCollsion:(SKSpriteNode *) node {
node.physicsBody.contactTestBitMask = racketHit;
}
-(void) touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent     *)event {
for (UITouch *touch in touches) {
    CGPoint location = [touch locationInNode:self];
    start = location;
    startTime = touch.timestamp;
    racketNode.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:racketNode.frame.size];
    racketNode.physicsBody.categoryBitMask = racket;
    racketNode.physicsBody.contactTestBitMask = HitIt;
    racketNode.physicsBody.dynamic = NO;
    racketNode.physicsBody.affectedByGravity = NO;
    [racketNode runAction:[SKAction moveTo:location duration:0.01]];
 }
}
- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
racketNode.physicsBody = nil;
racketNode.speed = 0;
}
-(void) touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent             *)event {
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
CGFloat dx = location.x - start.x;
CGFloat dy = location.y - start.y;
CGFloat magnitude = sqrt(dx*dx+dy*dy);
// Determine time difference from start of the gesture
CGFloat dt = touch.timestamp - startTime;
// Determine gesture speed in points/sec
CGFloat speed = magnitude/dt;
racketNode.speed = speed;
[handNode runAction:[SKAction moveTo:[touch locationInNode:self]   duration:0.01]];
} 

请告诉我,我的代码哪部分错了,使相同的对象只在高速碰撞,而不是在低速碰撞,也没有在稳定状态碰撞

使用UIPanGestureRecognizer来处理您的滑动,而不是手动操作。有了它,你可以使用一个velocity属性来检查速度是否大于给定值。

这里有一个很好的教程:https://www.raywenderlich.com/76020/using-uigesturerecognizer-with-swift-tutorial

最新更新