Reputation: 721
I have a sprite that looks like this.
How would I create an SKPhysicsBody for this sprite? I want it so that the SKPhysicsBody either is a triangle or it is just an edge on the long side of the sprite. Here is what I have so far. The sprite, called rightEnemy, has an anchor point of
CGPointMake(0.5, 0.5);
rightEnemy.physicsBody = [SKPhysicsBody bodyWithEdgeFromPoint:CGPointMake(rightEnemy.position.x + width, rightEnemy.position.y) toPoint:CGPointMake(rightEnemy.position.x, rightEnemy.position.y + height)];
This creates a physics body but for some reason it is not attached to the sprite.
The sprite that the physics body is attached to is moving constantly via the update method. The y value is always changing.
Upvotes: 3
Views: 473
Reputation: 1865
Here is the Swift version of the answer.
var trianglePath:CGMutablePathRef = CGPathCreateMutable()
CGPathMoveToPoint(trianglePath, nil, -self.size.width/2, self.size.height/2)
CGPathAddLineToPoint(trianglePath, nil, self.size.width/2, -self.size.height/2)
CGPathAddLineToPoint(trianglePath, nil, -self.size.width/2, -self.size.height/2)
CGPathAddLineToPoint(trianglePath, nil, -self.size.width/2, self.size.height/2)
self.physicsBody? = SKPhysicsBody( polygonFromPath: trianglePath)
Upvotes: 3
Reputation: 11696
You can create a triangle shaped physics body like this:
CGMutablePathRef trianglePath = CGPathCreateMutable();
CGPathMoveToPoint(trianglePath, nil, -myNode.size.width/2, myNode.size.height/2);
CGPathAddLineToPoint(trianglePath, nil, myNode.size.width/2, -myNode.size.height/2);
CGPathAddLineToPoint(trianglePath, nil, -myNode.size.width/2, -myNode.size.height/2);
CGPathAddLineToPoint(trianglePath, nil, -myNode.size.width/2, myNode.size.height/2);
myNode.physicsBody = [SKPhysicsBody bodyWithPolygonFromPath:trianglePath];
CGPathRelease(trianglePath);
The above creates a 45 degree right facing triangle.
Upvotes: 1
Reputation: 3812
You may want to try to create the physical body from the texture.
rightEnemy.physicsBody = [SKPhysicsBody bodyWithTexture:rightEnemy.texture size:rightEnemy.size];
You can also do this to validate if the physics is set correctly.
self.scene.view.showsPhysics = YES;
Edit
For iOS 7
Untested but I would imagine the bodyWithEdgeFromPoint: needs to be in the sprites coordinate system. You could try this which "should" draw a line from the bottom left to the top right corners of your sprite.
rightEnemy.physicsBody = [SKPhysicsBody bodyWithEdgeFromPoint:CGPointMake(-rightEnemy.size.width/2, -rightEnemy.size.height/2) toPoint:CGPointMake(rightEnemy.size.width/2, rightEnemy.size.height/3)];
Hopefully that helps.
Upvotes: 1