SpriteKit物理不匹配图像

时间:2018-04-17 21:05:44

标签: ios swift sprite-kit

在我的Pong游戏中,球没有正常弹跳。所以,在View Controller中,我将View的showPhysics设置为true,这就是我得到的图像:

enter image description here

这些拨片已在我的代码中调整大小:

override func didMove(to view: SKView) {

    // Create sprites
    ball = self.childNode(withName: "ball") as! SKSpriteNode
    enemy = self.childNode(withName: "enemy") as! SKSpriteNode
    player = self.childNode(withName: "player") as! SKSpriteNode

    // Get labels
    enemyLabel = self.childNode(withName: "enemyScore") as! SKLabelNode
    playerLabel = self.childNode(withName: "playerScore") as! SKLabelNode

    // Set constraints
    setConstraints()

    // Screen border
    let border = SKPhysicsBody(edgeLoopFrom: CGRect(x: frame.minX, y: frame.minY - ball.frame.height * 2, width: frame.width, height: frame.height + ball.frame.height * 4))
    border.friction = 0
    border.restitution = 0
    self.physicsBody = border

    // Reset game
    reset()

}

和我的setConstraints功能:

func setConstraints() {

    let enemyPositionY = SKConstraint.positionY(SKRange(constantValue: frame.maxY - 15))
    enemy.constraints = [enemyPositionY]
    enemy.size.width = frame.width / 4

    let playerPositionY = SKConstraint.positionY(SKRange(constantValue: frame.minY + 15))
    player.constraints = [playerPositionY]
    player.size.width = frame.width / 4

}

因此,我可以告诉我,当我调整我的精灵大小时,物理边界不会改变。我该如何解决这个问题?

这是一种奇怪的行为,但感谢您的帮助!

修改

Physics Definition(全部在属性检查器中完成):

enter image description here

==编辑(解决方案)==

谢谢。现在,我创建了一个重置​​physicsBody

的函数
import Foundation
import SpriteKit

// Create new default physics body
func createPhysicsBody(for body: inout SKSpriteNode) {

    // Create new physics body
    body.physicsBody = SKPhysicsBody(rectangleOf: body.frame.size)
    body.physicsBody?.isDynamic = false
    body.physicsBody?.allowsRotation = false
    body.physicsBody?.pinned = false
    body.physicsBody?.affectedByGravity = false
    body.physicsBody?.friction = 0
    body.physicsBody?.restitution = 0
    body.physicsBody?.linearDamping = 0
    body.physicsBody?.angularDamping = 0

}

要打电话,你可以使用:

createPhysicsBody(for: &player)

修改

我现在转到this,这是一种更简单的屏幕布局方式。

1 个答案:

答案 0 :(得分:2)

PhysicsBodies不是动态的。当您更改SKSpriteNode时,它们不会更改。您需要重新思考如何创建物理实体。您要么必须在编辑器中提出正确的大小并坚持使用它,要么在调整代码中播放器的大小后必须调整physicsBody矩形。

player.physicsBody = SKPhysicsBody(rectangleOf: player.frame.size)