0

In my Pong game, the ball is not properly bouncing. So, in the View Controller, I set the View's showPhysics to true, and this is the image I got:

enter image description here

These paddles have been resized in my code:

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()

}

and my setConstraints function:

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

}

So from this, I can tell that when I resize my Sprite, the physics boundaries do not change. How can I fix this?

This is strange behaviour, but thanks for any help!

EDIT

The Physics Definition (all done in the Attributes Inspector):

enter image description here

.

== EDIT (solution) ==

Thank you. Now, I have created a function to reset the 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

}

And to call it, you use:

createPhysicsBody(for: &player)

EDIT

I have now moved on to this which is a much easier way of doing the screen layouts.

George
  • 25,988
  • 10
  • 79
  • 133

1 Answers1

2

PhysicsBodies are not dynamic. They will not change when you alter a SKSpriteNode. You will need to rethink how you create your physics bodies. You either will have to come up with a correct size in the editor and stick with it, or you will have to adjust the physicsBody rectangle after you adjust the size of the player in code.

player.physicsBody = SKPhysicsBody(rectangleOf: player.frame.size)
Ron Myschuk
  • 6,011
  • 2
  • 20
  • 32