swift - 如何让 Sprite 坐在移动的 Sprite 上

标签 swift sprite-kit

如何让一个 Sprite 坐在一个移动的 Sprite 上并跟着它移动。我让红色盒子一时冲动跳了起来,当它落在正在移动的黑色方 block 上时,红色盒子会停留在它掉落的位置,就像没有摩擦力一样滑过移动的物体。在重力条件下,两者的摩擦力都为 1.0,甚至尝试增加质量,但没有任何效果。请给我任何细节如何让它工作? 谢谢 重写 func didMoveToView(view: SKView) { /* 在这里设置你的场景 */

    self.physicsWorld.gravity = CGVectorMake(0.0, -9.8)
    SquareOne.fillColor = UIColor.orangeColor()
    SquareOne.position = CGPoint(x: self.frame.midX, y: self.frame.midY)
    SquareOne.physicsBody = SKPhysicsBody(rectangleOfSize: SquareOne.frame.size)
    SquareOne.physicsBody?.friction = 1.0
    SquareOne.physicsBody?.restitution = 0.0

    addChild(SquareOne)


    SquareTwo.fillColor = UIColor.greenColor()
    SquareTwo.position = CGPoint(x: self.frame.midX, y: self.frame.midY - 100)
    SquareTwo.physicsBody = SKPhysicsBody(rectangleOfSize: SquareTwo.frame.size)
    SquareTwo.physicsBody?.dynamic = false
    SquareTwo.physicsBody?.affectedByGravity = false
    SquareTwo.physicsBody?.friction = 1.0
    SquareTwo.physicsBody?.restitution = 0.0
    addChild(SquareTwo)

}

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    /* Called when a touch begins */

    for touch in (touches as! Set<UITouch>) {
        let location = touch.locationInNode(self)
        SquareTwo.runAction(SKAction.moveByX(-100, y: 0.0, duration: 3.0))
    }
}

How i want it to work

最佳答案

在物理模拟中,您应该应用速度和力以使模拟正常工作。使用 SKAction 无法正确模拟物理现象。

首先,SquareTwo 需要动态化,以便受力影响。使 SquareTwo 的质量变大,这样 body 就不会受到与其碰撞的另一个 SquareOne 的影响。

SquareTwo.physicsBody?.dynamic = true
SquareTwo.physicsBody?.affectedByGravity = false
// Make the mass big so that the body is not affected by the other body colliding with it.
SquareTwo.physicsBody?.mass = 1000000

然后在 touchesBegan 中,您可以将速度设置为 SquareTwo

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    /* Called when a touch begins */

    for touch in (touches as! Set<UITouch>) {
        let location = touch.locationInNode(self)
        SquareTwo.physicsBody?.velocity = CGVectorMake(-10, 0)
     }
}

关于swift - 如何让 Sprite 坐在移动的 Sprite 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32513802/

相关文章:

ios - 从Firebase调用数据所需的完成处理程序?

ios - Swift 初始化不同类型的数组

ios - UICollectionViewCompositionalLayout 不能使用与 UICollectionViewDiffableDataSource 相同的部分吗?

json - 如何使用 "username"更改导航项标题?

ios - swift 3 : Making a Pause Menu in SpriteKit by overlaying a SKView?

ios - 是否可以在 Sprite Kit 中将一个场景推到另一个场景之上?

Swift/SpriteKit - 有什么方法可以池化/缓存 SKReferenceNodes 吗?

ios - 有没有办法使 SKSpriteNode 旋转与另一个 SKSpriteNode 物理体平行?

ios - 如何快速压缩视频?

ios - SKPhysicsBody 质量变化中心