Is it possible to place the physical body in only one part of the sprite?

Can a physical body be placed on a sprite? I want a certain part of my node sprite to have collision detection, and not the whole image.

Here is my physical body

physicsBody = SKPhysicsBody(rectangleOfSize: CGSize(width: CGFloat(54.0), height: CGFloat(100.0)))

But I want to place the physical body at the top of the node, where it usually fits in the middle of the node.

+4
source share
2 answers

You can try to create a smaller SKSpriteNodeone of the same size as SKPhysicsBody, and add a larger one SKSpriteNodeas a child to a smaller one. Change the position of the larger as you want. for example

override func didMoveToView(view: SKView) {

    let smallerSprite = SKSpriteNode(color: UIColor.redColor(), size: CGSizeMake(30, 30))
    smallerSprite.physicsBody = SKPhysicsBody(rectangleOfSize: smallerSprite.size)
    smallerSprite.position = CGPointMake(100, 400)
    self.addChild(smallerSprite)

    let largerSprite = SKSpriteNode(color: UIColor(white: 0.5, alpha: 0.5), size: CGSizeMake(100, 100))
    largerSprite.position = CGPointMake(-10, -10)
    smallerSprite.addChild(largerSprite)

    self.physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame)

}
+4
source

rakesh ... + bodyWithRectangleOfSize: center: method. :

override func didMoveToView(view: SKView) {

let sprite = SKSpriteNode(color: SKColor.whiteColor(), size: CGSize(width: 100.0, height: 100.0))

//I assume that you have initialized view and scene properly. If  so, this will position a sprite in the middle of the screen.
sprite.position = CGPoint(x: CGRectGetMidX(frame), y: CGRectGetMidY(frame))
var physicsBodySize:CGSize = CGSize(width: sprite.size.width, height: 30.0) //Create a size here. You can play with height parameter.

sprite.physicsBody =
    SKPhysicsBody(rectangleOfSize: physicsBodySize, center: CGPoint(x: 0.0, y: sprite.size.height / 2.0 - physicsBodySize.height / 2.0))

//Not needed, just set to restrict that sprite can't off screen
sprite.physicsBody?.affectedByGravity = false
self .addChild(sprite)

}

:

enter image description here

10.0, - :

enter image description here

+3

Source: https://habr.com/ru/post/1611762/


All Articles