OGeek|极客世界-中国程序员成长平台

标题: ios - 在 SpriteKit 中保持动态物理对象仍在手指下 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:41
标题: ios - 在 SpriteKit 中保持动态物理对象仍在手指下

我正在用 spritekit 开发一个相对简单的 child 游戏,比如虚拟玩具屋。在这个游戏中,他们是纸质人物,但也有一些互动对象,如弹力球。目前,我可以在移动手指时给出球的速度,并且球跟上我移动的手指。但是,当我的手指(握住球)静止在屏幕上的一个位置时,球会变得不稳定并开始在整个房间内跳跃或从我的手指中掉出。我通过将 isDynamic 设置为 false 来解决这个问题,同时将它们保持在我的手指上并将它们的位置更新到我的手指上,但是对于球来说不能这样做,因为它会阻止速度工作。我已经包含了 moveChar 和 moveBall 函数,因此您可以看到它们的区别,以及调用它们的位置 touchesMoved。谢谢!

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
//        print("Ball velocity is: ", ball.physicsBody?.velocity as Any)
    if let touch = touches.first {
        let location = touch.location(in: self)
        let startLocation = touch.previousLocation(in: self)
        if let sprite = currentSpriteHeld {
            if sprite == ball {
                moveBall(sprite: sprite, to: location)
            } else {
                moveChar(sprite: sprite, to: location)
            }
        } else {
            let impulse = CGFloat(2.0)
            let dx = (impulse * (startLocation.x - location.x))
            let dy = (impulse * (startLocation.y - location.y))
            let cameraPos = desiredPosition;
            let newCameraPos = CGPoint(x: cameraPos.x+dx, y: cameraPos.y + dy);
//                cameraNode.position = newCameraPos
            desiredPosition = newCameraPos
        }
    }

}

func moveBall(sprite: SKSpriteNode, to location: CGPoint) {
    ball.physicsBody?.velocity = CGVector(dx: 0.0, dy: 0.0)
    let distance = CGDistance(from: sprite.position, to: location);
    print("CGDistance is: ", distance)
    if distance > 10.0 {
        let dx = location.x-sprite.position.x;
        let dy = location.y-sprite.position.y;
        let drag:CGFloat = 0.01
        var vel = CGVector(dx: dx/drag, dy: dy/drag)
        vel = velocityCheck(vel: vel);
        sprite.physicsBody!.velocity = vel
    } else {
        ball.position = location;
    }
}

func moveChar(sprite: SKSpriteNode, to location: CGPoint) {
    if (sprite == dad) {
        dad.texture = dadPickup
    }
    sprite.physicsBody?.isDynamic = false;
    sprite.zPosition = 2;
    sprite.position = location
    touchPoint = location;
}

已解决:我通过将 moveBall 移动到触摸结束来解决此问题。现在我可以像握住 Sprite 一样握住球,并且仅在松开时才应用速度(导致晃动)。



Best Answer-推荐答案


已解决:我通过将 moveBall 移动到触摸结束来解决此问题。现在我可以像握住 Sprite 一样握住球,并且仅在松开时才应用速度(导致晃动)。

关于ios - 在 SpriteKit 中保持动态物理对象仍在手指下,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48529501/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4