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:
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):
.
== 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.