How to Use The Spritekit Method Body(At: Cgpoint)

SpriteKit - How do I check if a certain set of coordinates are inside an SKShapeNode?

The easiest solution specific to Sprite Kit is to use the SKPhysicsWorld method bodyAtPoint:, assuming all of the SKShapeNode also have an appropriate SKPhysicsBody.

For example:

SKPhysicsBody* body = [self.scene.physicsWorld bodyAtPoint:CGPointMake(100, 200)];
if (body != nil)
{
// your cat content here ...
}

If there could be overlapping bodies at the same point you can enumerate them with enumerateBodiesAtPoint:usingBlock:

Swift: Calculate how much to rotate an SKSpriteNode to have it pointing at a CGPoint

Long ago, after a lot of mind tweaking math and a sleepless night, I came up with this function:

func gunAngle(gunPosition: CGPoint, targetPosition: CGPoint) -> CGFloat {
let deltaX = Float(targetPosition.x - gunPosition.x)
let deltaY = Float(targetPosition.y - gunPosition.y)
let pi = CGFloat(M_PI)
let angle = CGFloat(atan2f(deltaY, deltaX))
var newAngle = angle

if angle < (-pi / 2) {
newAngle += 2 * pi
}
return newAngle - pi/2 // Subtracting 90 degrees out of the resulting angle, as in SpriteKit 0 degrees faces left, unless you rotate your gun in the sprite accordingly
}

I realize this may not be the best method but it works for me. Some math gurus could probably come up with something really brilliant here. I'm not yet any of those.

Thanks to Ray Wenderlich, on his website there is a tutorial on that topic that helped me a lot in putting the foundation of that math.

SpriteKit Nodes with Gravity False tilted in place

Well, Thanks to @RonMyschuk and @Knight0fDragon I found out (didn't know before) that I could add to my Scene loading the following:

skView.showsPhysics = true

Which add border lines around the physicsBody of your nodes, that way you can see them interacting. And by doing that I saw that the physicsBody of one of my nodes was completely in a different position then it should

Borderline around physicsBody

By taking care of this issue, everything went back to normal

Changing center point of SKPhysicsBody while using 'bodyWithTexture' (SpriteKit)

Anchor points have no effect on a physics body. There are a couple of physics bodies for which you can define a center point.

(SKPhysicsBody *)bodyWithCircleOfRadius:(CGFloat)r
center:(CGPoint)center

(SKPhysicsBody *)bodyWithRectangleOfSize:(CGSize)s
center:(CGPoint)center

Unfortunately the bodyWithTexture: has no such capability. As a hack you could use a number of various sized rectangles, rotate them to the desired angle and join them together with (SKPhysicsBody *)bodyWithBodies:(NSArray *)bodies. This will allow you to pretty much cover your texture.

As an added benefit, using rectangles instead of bodyWithTexture is also less of a burden to your FPS.



Related Topics



Leave a reply



Submit