How to Fit the Physics Body Size of an SKSpriteNode to its Image in Xcode Using SpriteKit

╄→尐↘猪︶ㄣ 提交于 2019-12-20 07:20:58

问题


So I'm not sure if this is possible, but I am trying to adapt the physics body to go with my image. Many people have told me that the hitbox for the character in my game on the iOS App Store (StreakDash - go download it!) does not work well, since it makes the game a lot harder (the hitbox hits an obstacle even though the character doesn't appear to even be touching it). This is due to the fact that the hitboxes are rectangular, whereas my character has a strange shape. Are there any ways to go around this? I thought of some ways that didn't completely work (e.g. trying to change the actual frame/canvas shape from rectangular to something else, trying to change the hitbox shape/size, trying to alter the image, etc.). It would be great if I could have advice on whether or not I should even change the hitbox in the first place (is it the type of rage-inducing game that makes people want to keep playing or stop?). But finding a way to solve the problem would be best!

Here is a picture of my character with its hitbox:

Here is just some basic code of with the SKSpriteNode and physics body:

 sprite = [SKSpriteNode spriteNodeWithImageNamed:@"stick"];
 sprite.size = CGSizeMake(self.frame.size.width/6.31, self.frame.size.height/3.2);
 sprite.physicsBody =[SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake (sprite.size.width, sprite.size.height)];
 sprite.position = CGPointMake(self.frame.size.width/5.7, self.frame.size.height/2.9);
 sprite.physicsBody.categoryBitMask = personCategory;
 sprite.physicsBody.contactTestBitMask = lineCategory;
 sprite.physicsBody.dynamic = NO;
 sprite.physicsBody.collisionBitMask = 0;
 sprite.physicsBody.usesPreciseCollisionDetection = YES;

回答1:


I suggest to represent the physic body with a polygon shape. You have two ways to improve bodyWithRectangleOfSize:

  1. The Lazy way is to use bodyWithTexture:size: which will create a physics body from the contents of a texture. But as Apple suggested, the more complex your physic body is , the more work to be properly simulated. You may want to make a tradeoff between precision and performance.
  2. The more proper way is to represent the bounding of your sprite with a convex polygon shape. See bodyWithPolygonFromPath:. There are some tools online to generate the path code in user interface. Here is the one: SKPhysicsBody Path Generator (be careful with the offset and anchor point). If you know the way to generate CGMutablePathRef code yourself, it will be easier to fit your situation.


来源:https://stackoverflow.com/questions/31900267/how-to-fit-the-physics-body-size-of-an-skspritenode-to-its-image-in-xcode-using

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!