endless runner game like dino rush object placement in cocos2d - cocos2d-iphone

My game is mostly already completed, but I need some changes related to the placement of objects. I have the same objects like the dinorush game. Like (fruit, block, missile, ball etc). I need proper placement of all objects like in the dino rush game. Currenly I am using random positions and movement of objects. I have not used any physics in my game. Also if I design placement using a tile map, then can we have magnet effects when my player stands near to the banana object? (I mean all banana automatically are attracted by the player)
Please help me. I am newbie in cocosd. This is my first game in cocos2d.

You can add a new class inherited the ccNode named magnet(banana) then add it to your game.Calculate the distance between the player and the banana.If the distance is less than the number you want, then move it to the player.
-(void)update:(ccTime)delta
{
float distance = ccpDistance(self.position, player.position);
if(distance < d){
CCAction *action = [CCMoveTo actionWithDuration:1.0f position:player.position];
[self addChild:action];
}
}

Related

Spritebuilder physics

ive run into some trouble with my spritebuilder project and i cant find a workaround. Im using the flappyfly tutorial to create a game.
In the tutorial there is an Obstacle.ccb in spritebuilder and obstacle.h/m in xcode. The obstacles get spawned into the main scene with this code
- (void)spawnNewObstacle {
CCNode *previousObstacle = [_obstacles lastObject];
CGFloat previousObstacleXPosition = previousObstacle.position.x;
if (!previousObstacle) {
// this is the first obstacle
previousObstacleXPosition = firstObstaclePosition;
}
Obstacle *obstacle = (Obstacle *)[CCBReader load:#"Obstacle"];
obstacle.position = ccp(previousObstacleXPosition + distanceBetweenObstacles, 0);
[obstacle setupRandomPosition];
obstacle.zOrder = DrawingOrderPipes;
[_physicsNode addChild:obstacle];
[_obstacles addObject:obstacle];
}
What i want to accomplish is to have these obstacles still spawning randomly. I dont want my hero to collide with the obstacles, instead i want the obstacles to act as a physics body, so you can jump on it, the problem is that when i disable hero and obstacle collision, the mainscene still imports the obstacles.m but no physics is being applied, even though physics is on in the obstacles.ccb, and the hero is able to go through the obstacles. The only way i can make it an actual physics body is to add the obstacles.ccb to the mainscene.ccb under the physics node. This works but then of course obstacles dont spawn randomly. Any workaround?
If you want them to keep spawning and for your hero to be able to jump on them without having to go to game over, i suggest setting a collision group for them

How to add "invisible walls" with SDL2

Se we are programming a game and in the center of the map there's area where the player cant go.
How we should create that area?
Game is top down perspective.
Assuming you are using some kind of collision detection that stops the player from going certain places (like off screen), all you have to do is to add an object that you can check for collisions with for the area where you don't want to player to go. Given that you haven't provided any specific information on how your game works this is the most specific answer you're likely to get.
Make an SDL_Rect that encompasses the entrance to the area, then check the collision of the SDL_Rect and the player
You will need some kind of collision detection as already mentioned above.
Then when moving the player, just check if the new position would collide with the rectangle in the middle of the screen.
Something like...
if( Input == Walk_Right)
{
//Move Player
MovePlayerRight();
//If Player collides with MiddleRect, move back
if (CheckCollison(&PlayerRect, &BoxRect) == true) MovePlayerLeft();
}
Check online for Collusion Detection. Simple Box Method should be enough to check if two Rectangles touch.

Iterating through a list of a super class while allowing removal and cast as subtype

I am writing an engine for older arcade games. Along with the engine I am writing Space Invaders. The idea is to leave the classes that comprise the engine generic enough to be adaptable to a wide variety of arcade games and then specific games like Space Invaders extend the engine and fill in the specific parts.
I have a game engine developed into two abstract classes that create a game loop and update sprites based on the elapsed time in between loop successions. In a class of the game engine, I have a resource manager that contains lists of Sprites for enemies, enemy projectiles, and player projectiles. The resource manager currently stores these lists as ArrayLists of type Sprite. The game engine then, in an update method, iterates through these lists of Sprites and updates the Sprites.
I then began working on Space Invaders and realized I needed to extend Sprite for my player ship (lives, player states) and also needed to extend Sprite for the aliens(points, alien states). I can still store my player as a Sprite in the resource manager and when I need to work with the player in the SpaceInvaders class I can call ResourceManager.getPlayer() which returns the player as a Sprite, but then I can cast it to a Player.
The problem arises when I try to work with the aliens. I made an Alien class that also extends Sprite. When I create the aliens, I create them as Alien objects and then pass them to the resource manager which stores them in the ArrayList of type Sprite. In my collision check method I iterate through the list of aliens as such:
for (Iterator<Sprite> iter = resources.getPlayerProjectiles().iterator();
iter.hasNext();) {
boolean shotRemove = false;
Sprite sprite = iter.next();
for (Iterator<Sprite> iterAlien = resources.getEnemies().iterator();
iterAlien.hasNext();) {
Sprite alien = iterAlien.next();
if (collision(sprite,alien)) {
shotRemove = true;
iterAlien.remove();
}
}
if (sprite.getY() < 100 || shotRemove)
iter.remove();
}
At this point I would like to use methods exclusive to Alien like writing score += alien.getPoints() below the shotRemove = true line. But the method only knows of alien as a Sprite because iterAlien is an iterator of type Sprite because resources.getEnemes() is a list of type Sprite. If I try to cast alien as an Alien I get a classCastException.
So in summary, I would like to be able to keep the lists in the resource manager as generic as possible (Sprite) because the engine only knows of Sprites, but be able to work with the lists when I iterate through them in game specific classes as the class which extends Sprite (in this case, Alien).
I have tried using generics like E extends Sprite in the resource manager, but I cannot get that to work. I have read a little bit about wildcards (?) but I don't think that is what I want to do. I would think E extends Sprite is what I want because then the list is of some generic type that extends Sprite and could be treated as either a Sprite (in the engine) or as the E (Alien in SpaceInvaders).
You can't guarantee that the Sprite is an Alien, so use instanceof, something like:
if (sprite instanceof Alien) {
Alien alien = (Alien)sprite;
// do something with alien
}
Generics can't help you further here.

Game object with composition and CCSpriteBatchNode

I'm currently developing a game with cocos2d and box2d on iPhone.
I read a lot of articles concerning game code organization, game objects structure etc.
I first started developing my game objects by inheriting from a base class itself inheriting from CCSprite.
I had a CCSpriteBatchNode to draw all the game items, which the player can interact with, in one draw call. This was easy because my Item class indirectly inherit from CCSprite so I could easily add my items to the CCSpriteBatchNode. And on top of that I could rely on cocos2d to retain my objects.
After I read the articles, I understood the need to refactor my code with a more composition oriented style rather than the inheritance style.
So I went with a GameObject base class inherited from NSObject and having properties such as one or more CCSprite, one b2Body etc.
The problem I'm facing now is that I can't directly add my GameObject to the CCSpriteBatchNode anymore. I first thought I could easily fix the problem by adding the sprite property of the GameObject to the CCSpriteBatchNode. It's ok but who retains the object owning the CCSprite ? How can I easily access the original object from the CCSprite (are userData/Object ok) ?
Should I create an array retaining my items ?
I'd like to know how you would use a CCSpriteBatchNode with such a game object structure ?
There is already a thread about that which is unanswered and I'd really like to hear about the subject. Not a straight answer but some elements to go further.
Thanks.
Personally I don't recommend using NSObject as the base class for cocos2d classes anymore. Simply because you lose some cocos2d convenience features such as scheduling and you can easily shoot yourself in the foot, memory-management wise.
What you want is a setup where the scene has one or more sprite batch nodes. You can consider them layers for your sprites. Your actual game objects (consider them to be MVC controllers) deriving from CCNode can be added anywhere, typically directly to the scene.
scene
+ batch node 1
+ sprite 1
+ sprite 2
+ sprite n
+ batch node 2
+ sprite 1
+ sprite 2
+ sprite n
+ game node 1
+ game node 2
+ game node 3
+ game node n
The thing to keep in mind is that each game node has one or more sprites as instance variables, but they're not childs of the node. So for example the game node 1 class might look like this:
game node 1 class
CCSprite* sprite1; // instance variable
CCSprite* sprite2; // instance variable
Now when you init game node 1 and its sprites, you add the sprites to the appropriate sprite batch node. Typically you will want to access your scene like a singleton to get access to its sprite batch properties.
sprite1 = [CCSprite spriteWithSpriteFrameName:#"doodle.png"];
[[scene sharedScene].batchNode1 addChild:sprite1];
sprite2 = [CCSprite spriteWithSpriteFrameName:#"splash.png"];
[[scene sharedScene].batchNode2 addChild:sprite2];
Note that you do not need to retain the sprites as long as they are children of the sprite batch node. The addChild method retains it for you. Actually, it just adds it into an array which does the retaining. Also, if you're still thinking about "retain", by all means start using ARC.
You do not need to figure out how to access the sprite in the sprite batch. It's available as an instance variable of your game node class, and if you wish, you can also make it publicly available to other classes as a property.
The game node class obviously runs all the object's game logic, including positioning and otherwise modifying the sprite's properties. The only thing you need to take care of in the game node class is that you remove the sprites from the batch node, otherwise it may be leaking. To do so, override the cleanup method:
-(void) cleanup
{
[sprite1 removeFromParentAndCleanup:YES];
sprite1 = nil;
[sprite2 removeFromParentAndCleanup:YES];
sprite2 = nil;
[super cleanup];
}
It's important to set the variables to nil because there may be code running after cleanup, including the code in the dealloc method. You could also remove the sprites in dealloc but depending on your setup, dealloc may not even get called because of the references to the sprite the game node class is still holding. Therefore it is generally safer to use the cleanup method if the sprites are not children (or grandchildren) of the game node class itself.

Move background - Cocos2D

I am trying to develop a car game in which opponents are coming from opposite direction. And we have to avoid collision. For this I want to move my background as the opponent cars approach the good car. What should I do to move the background?
Regards,
Stone
1.- You need to create a map: example with program "Tiled".
2.- Add to resources
3.- Insert code:
CCTMXTiledMap * tmxMap = [CCTMXTiledMap tiledMapWithGMXFile:#"Map.tmx"];
[tmxMap runAction:[CCMoveBy actionWithDuration:1.0 position:ccp(0,-400)];