如何拖放一个非常高的精灵而不让它跳到锚点?

问题描述 投票:0回答:1

我使用以下代码在我的 SpriteKit 场景中使用 Swift 移动一个非常高、薄的精灵。

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesMoved(touches, with: event)
    let touch = touches.first!
    let moveableNodeTouchLocation = touch.location(in: moveableNode)
    monkeySprite.position = moveableNodeTouchLocation

当我创建 MonkeySprite 时,我可以将锚点更改为 CGPoint(x: 1.0, y: 1.0) 或 0.5 或 0,无论锚点在哪里,当拖动触摸移动事件时,精灵都会“跳转”到该位置。

有没有办法将精灵从触摸的位置移开?我尝试将锚点更改为触摸位置,如下所示:

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesMoved(touches, with: event)
    guard let touch = touches.first, let touchedSprite = touchedSprite else { return }
    let location = touch.location(in: self)

    // Calculate the new anchor point based on the touch location and offset
    let newAnchorX = (location.x - touchOffset.x) / touchedSprite.size.width
    let newAnchorY = (location.y - touchOffset.y) / touchedSprite.size.height

    // Set the new anchor point
    touchedSprite.anchorPoint = CGPoint(x: newAnchorX, y: newAnchorY)

    // Adjust the sprite's position to keep it in the same visual location
    touchedSprite.position = location
}

但它并没有改变精灵最初跳跃的方式,以将前一个锚点定位到触摸事件的位置,然后在屏幕上平滑拖动以跟随之后移动的触摸。在初始触摸期间是否有不同的方法来建立新的锚点,或者我应该尝试不同的方法?

swift sprite-kit sprite draggable
1个回答
0
投票

感谢 bg2b 为我指明了正确的方向!以下作品:

private var sprite: SKSpriteNode!
private var initialTouchOffset: CGPoint = .zero
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
initialTouchOffset = CGPoint(x: location.x - sprite.position.x, y: location.y - sprite.position.y)
 }

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    guard let touch = touches.first, isDragging else { return }
    let location = touch.location(in: self)
    
    sprite.position = CGPoint(x: location.x - initialTouchOffset.x, y: location.y - initialTouchOffset.y)
}
© www.soinside.com 2019 - 2024. All rights reserved.