开发者

Cocos2d - Creating collidable Sprites?

Hello everyone I an very new to cocos2d, so I apologize if this is a simple question. I would like to create to sprites that collide when they hit each other.

For instance, one sprite, spriteA, is in a fixed position on the screen. And another sprite, spriteB, is moving around the scree开发者_JAVA百科n. SpriteB will collide with spriteA. If that doesn't make sense or you don't understand it, tell me and I will elaborate further. Any help is appreciated. Thank YOU!


Try using Chipmunk or Box2d physics systems. These are included with Cocos2d and work by having a physics simulation that updates with every time the graphics change on screen.

The physics simulation will tell you if two objects are overlapping, and will provide physical attributes like weight, slipperiness (friction), speed and direction, which creates reactions like bouncing, sliding, realistic loss of speed and changes of direction on impact.

If you are new to physics simulation, here's a 30 second run down:

  • Create "bodies" in the physics simulation that represent each graphical sprite
  • Bodies are usually defined more simply than their graphical counterparts, like a circle, square or simple polygon shape
  • In order to update the graphics on the screen accurately, first you establish a pixels to meters ratio. Meters are notional (i.e. made up) measurement that is used in the physics sim
  • Each time the physics simulation "ticks", you update the graphics on screen accordingly
  • So if a body in the physics sim moves 1 meter, you might transform the pixel sprite 32 pixels

Here's a good tute on collision detection using Box2d. http://www.raywenderlich.com/606/how-to-use-box2d-for-just-collision-detection-with-cocos2d-iphone

enjoy


Its actually very simple:

  1. Just schedule a timer: [self schedule:@selector(checkForCollision:)];

  2. Specify the method: - (void)checkForCollision:(ccTime)dt {}

  3. In the curly braces, make CGRects for each sprite using CGRectMake.

  4. Then in the same method, just call: if (CGRectIntersectsRect) {}

That easy!


Well technically speaking when the 2 sprites interact, or share at least one common point, then they are colliding. I'm a little confused by your question. Are you asking for direction on how to make the sprite move on screen, or are you asking how to handle the actual collision(such as calling a method if they collide)?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜