1

I created a subclass of SKNode:

class SquareDrop: SKNode {
    init(image: SKSpriteNode) {
        super.init()
        self.setScale(0.3
        //Set the starting position of the node 
        self.position = CGPoint(x: 0.5, y: UIScreen.main.bounds.height/2)
        //Apply a physics body to the node
        self.physicsBody = SKPhysicsBody(texture: SKTexture(imageNamed: "square"), size: CGSize(width: image.size.width * 0.3, height: image.size.height * 0.3))
        self.addChild(image)
}

I created an instance in GameScene class and I set up it:

func spawnRain() 
    squareDrop = SquareDrop(image: SKSpriteNode(imageNamed: "square"))
    squareDrop?.physicsBody?.linearDamping = 5
    squareDrop?.physicsBody?.restitution = 0
    self.addChild(squareDrop!)
}

It is the result:

Image A

It works like aspected, but instead of using an image I wanted to draw a square:

func spawnRain() {
    //Here I did not use the class that I had created previously
    let shape = SKShapeNode()
    shape.path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: 100, height: 100), cornerRadius: 5).cgPath
    shape.position = CGPoint(x: frame.midX - shape.frame.width/2 , y: UIScreen.main.bounds.height/2)
    shape.fillColor = UIColor.red
    shape.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: 100, height: 100))
    addChild(shape)
 }

enter image description here

It doesn't seem like I aspected (the squares that I created have a strange behaviour). Any hints? I am sorry for the question, but I am a noob of SpriteKit.

Edoardo
  • 657
  • 7
  • 24
  • 1
    It looks as though your physics bodies are not aligned with the nodes. Can you change `showPhysics` to `true` in your ViewController file? https://developer.apple.com/documentation/spritekit/skview/1520389-showsphysics – Steve Ives Sep 05 '18 at 12:31
  • @SteveIves Thank you, you are right, the bodies were not aligned with the nodes. – Edoardo Sep 05 '18 at 12:55
  • 1
    No problem - not sure why though without experimenting. Something to do with how the node's `shape` property is created from a path affecting the `anchor` property perhaps? – Steve Ives Sep 05 '18 at 12:57
  • @SteveIves I don't really know. The node's shape was not created from a path affecting an anchor property. I onlyset the path with CGRect where I input x, y, width and height. I think that I have to center the physicsBody to the square. – Edoardo Sep 05 '18 at 13:38
  • 1
    I suspect the physics body is centered on the node and the shape is not. Try this `shape.path = UIBezierPath(roundedRect: CGRect(x: -50, y: -50, width: 100, height: 100), cornerRadius: 5).cgPath` – 0x141E Sep 05 '18 at 20:16
  • 1
    Physicsbodies are relative to the nodes origin, so like 0x141E has pointed out, you need to shift your shape so that your box center is the same location as your nodes origin. – Knight0fDragon Sep 06 '18 at 13:15

0 Answers0