Cocos2d - Creating collidable Sprites? - iphone

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 screen. 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:
Just schedule a timer: [self schedule:#selector(checkForCollision:)];
Specify the method: - (void)checkForCollision:(ccTime)dt {}
In the curly braces, make CGRects for each sprite using CGRectMake.
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)?

Related

SpriteKit snake - joints and physics

I'm working on my game - Snake for iOS.
My development has already passed this stage, however I think about doing some refinements to it. After several tries and errors I've totally ignored physics/movement and collision detection offered by SpriteKit and I keep using my own implementation. Perhaps with your help I may refactor this parts of the game.
My snake can turn in all possible directions (360 degree). There is no gravity. How would you set up your physic bodies if you would prefer to offset as much as a code to existing SpriteKit implementation?
There are two important parts I think.
First - joints. Snake is constructed from multiple physic bodies. All bodies simply follow one another - going through all the points that the head was some time ago. I assume the best joint for this is Pin joint? I used Pin joints with anchor point exactly between neighbouring bodies. But this setup caused the rest of the snake's body to change the physics of the head. It shouldn't be like that. I tried changing the weight to zero, putting linear and angular dumping to maximum. The result was never acceptable.
Second - controlling movement. The movement of the snake is constant. User by pressing left and right button starts gentle movement of the snake to the right or left. Do you think I should in the update method reset the snake's velocity each time to my constant value? Or should I play with forces impulses and torques? The turning only takes place when user keeps pressing the screen - it takes few seconds to reverse the snake (like "u-turn") - how about rotating it?
Any suggestion is appreciated. Best regards.

Spritekit how to not veer off

I'm building a pacman style maze game.
I can apply impulse and limit it to whatever vertical or horizontal direction as desired on the hero.
However, when I add physics body sprites for walls, it gets weird.
I have set the hero physics body and the walls to have no bounce.
Running head on into a wall it stops dead like expected.
But if I then change direction and move along the wall I veer off at a slight angle from the wall.
Any ideas what causes this and how to avoid it?
I want to only move in vertical and horizontal straight lines.
Ok so the solution here is slightly counter intuitive.
Rather than using applyForce: or applyImpulse: family of methods on the physicsBody, use runAction:forKey: on the sprite itself.
For any change in direction, removeAction:forKey: just before calling runAction:forKey: to keep things orthogonal.
(Otherwise there will be a brief angular movement )
The other trick here is to find an appropriate speed for distance. Too fast and it will fly through walls. (Bug?)
Then apply the speed and distance with a multiplier based on the size of your scene.
The total distance should be something greater than possible in any direction.
That keeps the thing moving until it hits a wall or you tell it to move in a different direction.
This works really well.
Using the physics body movement, it seems best suited to a platformer situation where you have a gravity.
In a top down view, there isn't normally gravity.
( though it is imaginable that you could want something that exerts gravity on a sprite to suck it in)

Breaking up a sprite in cocos2d

I'm making a 2D plane fighting game for the iPhone in cocos2d. I'm trying to make it so when you shoot an enemy plane, it breaks into a couple of separated pieces that will fall out of sight. What is generally the best practice for breaking one sprite up into many? should I create new images for each separate piece, or treat the initial image like a sprite sheet, and make a new sprite from segments?
Please look at this tutorial
It makes a grid of points then moves the internal (not-edge) ones around randomly a bit so it's not all perfect triangles. Then each update it moves/rotates the triangles separately--then draws them all at once.
You treat the whole thing as a sprite, so can run any of the usual actions on it. This example uses CCMoveBy to move the whole group down off the bottom.

Create a space environment with no gravity, Box2d or not?

I want to create a cclayer with 4-5 flying objects, flying in random directions on screen. I also want those flying objects transparent to each other, which means they can fly through each other.
What I can think of Ways to do:
With Box2D
Create a box2d world with 0 gravity. and add Polygon static ground around the edges of the screen.
Give an initial force to each of the flying objects, let them flying around and reflect on the grounds.
Problems: Objects still rest down after sometime.. Don't know why. Objects collide with each other, don't know how to make them fly through each other.
Without Box2D
use CCMove for each objects, detect if they reach edge of the screen, calculate new path for their move..
Can someone point me a direction, which way is easier? Thanks a lot.
If you have to handle complex collisions - go with Box2d. If your collisions are simple - handle them yourself.

Iphone I am using cocos2d and need the rgba value of a pixel on a sprite

I am programing a shooter game in cocos2d for the iphone. I and I want to exclude collision detection an the alpha of my sprite.
How do I read the RGBA value of the single pixel.
Thanks for the help.
First off, think about if you really want to do this -- it's much more computationally expensive than other methods of collision detection (i.e, bounding box, circle collision) which may not be as accurate, but for most purposes work well enough.
If you really do want to do this, you should generate a mask for each of your sprites that you want to detect the collision between. This mask should ideally be a simple 1-bit representation of your sprite.
Next, for each sprite you want to check for a collision, you need to do a few steps:
Since the pixel accurate collision is going to take a long time, do a bounding box collision first between the two sprites to see if you even need to check for pixel level collision.
If you know the sprites have collided at the boundaries, calculate the rect of the collision. You may want to do an optimization at this stage that says if they are greater than X% overlapped that they have collided. Especially if your alpha areas of the sprite are along the outside edges.
Using the rect area of the collision, go through the masks of each of your sprite -- if both pixels are 1, you have a collision -- exit out of the loop and do what you need to mark them as collided.
As you can see, this is very CPU heavy compared to the other methods, which is why I recommended against it at the beginning. Unless a system has hardware support for pixel accurate collisions (the Atari 2600 actually had this), most games are not going to use pixel values for their collisions.
If you decide to go with a bounding box approach, you can do things like shrinking the bounding box used for collisions to prevent false positives for when two sprites touch each other at a corner.
Good Luck!
Not specific to Cocos2d, but should work on any iPhone project -- check out this question & answer