0

我有一个 SpriteKit 场景,其中一个SKFieldNode.linearGravityField(withVector:)SKSpriteNode一个physicsBody. 用户用手指移动精灵。

我通过显式设置其velocityin来移动精灵update(_:),这会导致一个问题:当用户的手指触摸屏幕时,该字段不会影响精灵,因为我的代码会覆盖它。当用户的手指没有触摸屏幕时,该字段将按需要工作。

这是我设置精灵的方式velocity

override func update(_ currentTime: TimeInterval) {
    //NOTE: intensityX and intensityY are based on how far the user has dragged their finger, and are set in touchMoved().

    if intensityX != 0.0 {
        mainCharacter?.physicsBody?.velocity.dx = intensityX
    }
    if intensityY != 0.0 {
        mainCharacter?.physicsBody?.velocity.dy = intensityY
    }
}

以下是我创建该字段的方式:

let field = SKFieldNode.linearGravityField(withVector: vector_float3(-9.0,0,0))

field.region = SKRegion(size: CGSize(width: screenWidth, height: screenHeight*0.1))
        
field.position = CGPoint(x: screenWidth, y: screenHeight*0.2)
        
addChild(field)

问题:即使精灵被用户移动,我如何才能使该字段影响精灵?

谢谢!

4

1 回答 1

0

这个问题的答案是对精灵施加一些力,physicsBody而不是明确设置它的速度。显式设置它的速度会覆盖场的物理特性,这是不好的。

update(_:),我现在正在使用applyForce(_:).

mainCharacter?.physicsBody?.applyForce(CGVector(dx: someForceX, dy: 0.0))

这允许用户在仍然体验场效果的同时移动精灵。

于 2022-01-25T10:15:50.350 回答