为什么当我使用带有图像的SKSpriteNode时它不会弹跳但是当我使用SKShapeNode时它确实有效?

时间:2016-07-13 16:37:02

标签: swift sprite-kit skspritenode

我是斯威夫特的新手,我正在尝试创造一个上下反弹的球。当我使用时:

import Foundation
import SpriteKit

class Ball {
    let movingObject: SKShapeNode

    init() {
        movingObject = SKShapeNode(circleOfRadius: 25)
        movingObject.physicsBody = SKPhysicsBody(circleOfRadius: 25)
        movingObject.physicsBody?.affectedByGravity = true
        movingObject.physicsBody?.restitution = 1
        movingObject.physicsBody?.linearDamping = 0

    }
}

它工作正常。但是,当我尝试使用图像时,它不会反弹。

class Ball {
    let movingObject: SKSpriteNode
    let picture: String

    init(picture: String) {
        self.picture = picture
        movingObject = SKSpriteNode(imageNamed: picture)
        movingObject.physicsBody = SKPhysicsBody(circleOfRadius: movingObject.size.width * 0.5)
        movingObject.physicsBody?.affectedByGravity = true
        movingObject.physicsBody?.restitution = 1
        movingObject.physicsBody?.linearDamping = 0

    }
}

2 个答案:

答案 0 :(得分:2)

你的两个物理体之间的唯一区别是半径。因此,这一直是问题所在。

尝试将半径设置为25,就像使用形状节点确认一样,然后尝试解释为什么movingObject.size.width * 0.5没有达到合理的值。您可以设置断点并使用调试器print movingObject.size来帮助。

答案 1 :(得分:1)

关于SKSpriteNode来源:

/**
     Initialize a sprite with an image from your app bundle (An SKTexture is created for the image and set on the sprite. Its size is set to the SKTexture's pixel width/height)
     The position of the sprite is (0, 0) and the texture anchored at (0.5, 0.5), so that it is offset by half the width and half the height.
     Thus the sprite has the texture centered about the position. If you wish to have the texture anchored at a different offset set the anchorPoint to another pair of values in the interval from 0.0 up to and including 1.0.
     @param name the name or path of the image to load.
     */
    public convenience init(imageNamed name: String)

在第一种情况下,您使用25作为半径,在下一步中您必须检查movingObject.size.width` * 0.5是否为有效度量。

当您处于调试阶段时,请尝试通过启用showsPhysics属性来帮助自己:

示例代码

override func viewDidLoad() {
        super.viewDidLoad()

        if let scene = GameScene(fileNamed:"GameScene") {
            // Configure the view.
            let skView = self.view as! SKView
            skView.showsPhysics = true
            ...
        }
}

您可以轻松查看对象的physicBody边界,如果出现问题,您可以立即注意到它。

enter image description here