簡體   English   中英

當手指在節點上時如何對精靈施加恆定的力,並在釋放時消除力

[英]How to apply constant force to a sprite when finger is on a node and cancel the force on release

在我的項目中,我想使用applyForce:方法移動_character ,當手指在button上時,希望將力不斷施加到_character上,但是我也不希望velocity超過一定值。

我嘗試了以下方法:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInNode:self];
    SKNode *node = [self nodeAtPoint:location];


        if ([node.name isEqualToString:@"moveRightButton"]){

            _held = YES;

            for (SKPhysicsContact* contact in [self.contactQueue copy]){

                [self handleContact:contact];
                [self.contactQueue removeObject:contact];

            }
            while (_held == YES) {
                [_character.physicsBody applyForce:CGVectorMake(1000, 0)];
            }
       }
    }

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{

    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInNode:self];
    SKNode *node = [self nodeAtPoint:location];

        if ([node.name isEqualToString:@"moveRightButton"]){

            _held = NO;

        }

}

_held是整個類中可訪問的ivar。

現在,當我運行此命令時,我遇到某種類型的內存泄漏,導致它使用大約3分鍾內達到7 GB的GB內存(可能是因為我使用CGVectoryMake:而不是每次都不會創建的CGVector變量集)當我單擊按鈕時,什么也沒有發生,但是當我沒有while語句時,它工作正常,但是我不得不不斷地按它才能到達某個地方。

在回答有關如何限制對象速度的問題時:

if(mySpriteA.physicsBody.velocity.dx > 50)
    mySpriteA.physicsBody.velocity = CGVectorMake(50, mySpriteA.physicsBody.velocity.dy);
if(mySpriteA.physicsBody.velocity.dx < -50)
    mySpriteA.physicsBody.velocity = CGVectorMake(-50, mySpriteA.physicsBody.velocity.dy);
if(mySpriteA.physicsBody.velocity.dy > 50)
    mySpriteA.physicsBody.velocity = CGVectorMake(mySpriteA.physicsBody.velocity.dx, 50);
if(mySpriteA.physicsBody.velocity.dy < -50)
    mySpriteA.physicsBody.velocity = CGVectorMake(mySpriteA.physicsBody.velocity.dx, -50);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM