Monsters/Enemies on Platforms(like on Doodlejump)Cocos2d - iphone

I'm new here so i hope you can help me.
I am following a tutorial on making simple cocos2d game
Ray Wenderlich's Tutorial
I implemented it on another game a jumping one like doodle jump.
in the said tutorial the monsters/targets are moving freely coming from the right to the left side of the screen. when i implement it on my app the monsters are like flying from left to right. What if i want the monsters to stand on the platforms just like the one on doodle jump? what particular things will i do?
PS:i tried some other things on google but none works
Here is the code of the monsters/targets:
- (void)initPlatforms {
// NSLog(#"initPlatforms");
currentPlatformTag = kPlatformsStartTag;
while(currentPlatformTag < kPlatformsStartTag + kNumPlatforms) {
[self initPlatform];
currentPlatformTag++;
}
[self resetPlatforms];
}
- (void)initPlatform {
CGRect rect;
switch(random()%2) {
case 0: rect = CGRectMake(608,64,102,36); break;
case 1: rect = CGRectMake(608,128,90,32); break;
}
AtlasSpriteManager *spriteManager = (AtlasSpriteManager*)[self getChildByTag:kSpriteManager];
AtlasSprite *platform = [AtlasSprite spriteWithRect:rect spriteManager:spriteManager];
[spriteManager addChild:platform z:3 tag:currentPlatformTag];
}
-(void)addTarget {
Sprite *target = [Sprite spriteWithFile:#"komodo.png"];
target.position = ccp(300,200);
[self addChild:target];
CGSize winSize = [[Director sharedDirector]winSize];
int minX = target.contentSize.height/2;
int maxX = winSize.height -target.contentSize.height/2;
int rangeX = maxX - minX;
int actualX = (arc4random() % rangeX) +minX;
int minDuration = 2.0;
int maxDuration = 4.0;
int rangeDuration = maxDuration - minDuration;
int actualDuration = (arc4random() % rangeDuration) + minDuration;
id actionMove = [MoveTo actionWithDuration:actualDuration position:ccp(-target.contentSize.width,actualX)];
id actionMoveDone = [CallFuncN actionWithTarget:self selector:#selector(spriteMoveFinished:)];
[target runAction:[Sequence actions:actionMove, actionMoveDone,nil]];
target.tag = 1;
[_targets addObject:target];
}
Thanks to those who will help... you are so nice.

This is a pretty broad question unfortunately, which makes it difficult to answer in any definitive terms. If you are hoping to create actual platforms that can be bounced on (in a doodle jump manner) you are going to need to implement collision detection between the Monsters and the Platform ccNodes. There are numerous tutorials online for cocos2d collision detection, both simple implementation and the more advanced box 2d/chipmunk based solutions.
If you are looking to clone doodle jump fairly closely, there is an open source version of a clone available on github here - though I've not actually looked at the code.
Finally, if you mean that you simply want to restrict the movement of the monsters to a particular area of the screen (so they don't keep running off the edge) you just need to position the target to an area on the screen and alter theccAction so that the ccMoveTo uses the left most point of the 'platform' as the furthest point left it can move to and the right most point as the furthest right. (I'll confess I've not played Doodle Jump so have no idea what the enemies actually do).
If the enemies run back and forth across the platform you should look into using ccRepeatForever on your movement sequence and have two destination positions in the CCSequence : one that moves the monster to the left of the platform, the other to move it to the right.
Additional Info
Ok, I see what you are trying to do. This should get you started:
Platforms are created in initPlatforms. This calls initPlatform a number of times. This grabs an image from the AtlasSprite for the platform, creates a ccSprite for each platform and assigns it a unique tag.
Then, in - (void)step:(ccTime)dt it loops through all the platforms and moves them to their correct location based on how far the bird has moved:
for(t; t < kPlatformsStartTag + kNumPlatforms; t++) {
AtlasSprite *platform = (AtlasSprite*)[spriteManager getChildByTag:t];
//etc...
So, the bit you are waiting for:
If you want to add a monster to these platforms, you will have to follow a similar pattern. To get started try something like this (You will want to have a cleaner design than this though but it should put you on the right track)
in initPlatform add the following to the end of the function
// add a monster sprite
AtlasSprite *monster = [AtlasSprite spriteWithRect:CGRectMake(608,128,64,64) spriteManager:spriteManager];
[spriteManager addChild:monster z:3 tag:currentPlatformTag + 1000];
(I've just grabbed an image from the existing Atlas. You could replace the above with your actual 'Monster' sprite object. Notice I add 1000 to thecurrentPlatformTag. This is just for testing; you should have a monsterTag implementation eventually.
So now every platform has a 'monster' (Again, you will only want to target random platforms)
so we need to update the positions for the monsters.
In - (void)step:(ccTime)dt directly after you get the current platform
AtlasSprite *platform = (AtlasSprite*)[spriteManager getChildByTag:t];
You now also need to get the current monster (remembering to use the updated tag value we created for 'monsters':
AtlasSprite *monster = (AtlasSprite*)[spriteManager getChildByTag:t + 1000];
Then, a few lines below where we reposition the platform we will need to reposition the monster
platform.position = pos;
// We update the monster and set it a 32 pixels above the platform:
monster.position = ccp(pos.x, pos.y + 32);
So now each platform has a monster on it whose y position moves with the the platforms :-)
Hope this helps

Related

SKSprite not positioning where it should

I've got a character in a game, and it's supposed to shoot a bullet. I've set everything up for the character, and have setup the path for the bullet to travel through. Here's the code I'm using:
//The destination of the bullet
int x = myCharacter.position.x - 1000 * sin(myCharacter.zRotation);
int y = myCharacter.position.y + 1000 * cos(myCharacter.zRotation);
//The line to test the path
SKShapeNode* beam1 = [SKShapeNode node];
//The path
CGMutablePathRef pathToDraw = CGPathCreateMutable();
//The starting position for the path (i.e. the bullet)
//The NozzleLocation is the location of the nozzle on my character Sprite
CGPoint nozzleLoc=[self convertPoint:myCharacter.nozzleLocation fromNode:myCharacter];
CGPathMoveToPoint(pathToDraw, NULL, nozzleLoc.x, nozzleLoc.y);
CGPathAddLineToPoint(pathToDraw, NULL, x, y);
//The bullet
SKSpriteNode *bullet = [SKSpriteNode spriteNodeWithTexture:bulletTexture size:CGSizeMake(6.f, 6.f)];
bullet.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:3 center:bullet.position ];
[bullet.physicsBody setAffectedByGravity:NO];
[bullet.physicsBody setAllowsRotation:YES];
[bullet.physicsBody setDynamic:YES];
bullet.physicsBody.categoryBitMask = bulletCategory;
bullet.physicsBody.contactTestBitMask = boundsCategory;
//These log the correct locations for the character
//and the nozzle Location
NSLog(#"myposition: %#",NSStringFromCGPoint(myCharacter.position));
NSLog(#"nozloc: %#",NSStringFromCGPoint(nozzleLoc));
bullet.position = [bullet convertPoint:nozzleLoc fromNode:self];
[self addChild:bullet];
NSLog(#"Bullet Position: %#",NSStringFromCGPoint(bullet.position));
[bullet runAction:[SKAction followPath:pathToDraw duration:6.f]];
//I'm using this to test the path
beam1.path = pathToDraw;
[beam1 setStrokeColor:[UIColor redColor]];
[beam1 setName:#"RayBeam"];
[self addChild:beam1];
This is what I get from the NSLogs I'm using above:
myposition: {122.58448028564453, 109.20420074462891}
nozloc: {145.24272155761719, 77.654090881347656}
Bullet Position: {145.24272155761719, 77.654090881347656}
So everything should work, right? But the issue that I'm having is that the bullets are shot from a slightly different location. You can see from the image below:
I aligned the character, so that the bullets start from that little square in the middle. This way you can see the distance from where the bullet are supposed to start (in front of the gun my character is holding), and the square in the middle of the screen.
The bullets travel correctly on a straight line, and the angle of the line is the same as the angel of the path ( the path and the line bullets form are parallel as you can see from the picture). When I move my line, the bullets also move in the same way. I think the issue is the point conversion between nodes, but I've tried both
[self convertPoint:myCharacter.nozzleLocation fromNode:myCharacter]
[bullet convertPoint:nozzleLoc fromNode: self]
[self convertPoint:nozzleLoc toNode:bullet]
However, they all result in the exact same starting point for the bullet. Do you know why I'm having this issue? Is it because I'm scaling down my character sprite using setScale (I'm setting it to 0.3)?
Thanks a lot in advance for your help.
This isn't your issue but nozzleLoc is already in the scene's coordinate space so it should be:
bullet.position = nozzleLoc;
This will save a quick second conversion from having to be calculated.
followPath:duration: is the same as followPath:asOffset:orientToPath:duration: with asOffset: YES -- it's using your current position as the origin of the path. See the documentation here.
To fix it you'll want the asOffset to be NO (requires the full method call above) or you can leave it as is and take out the line of code setting the bullet's position.

sneakyinput not reading button when joystick is held down

I have a problem with SneakyJoystick and SneakyButton. SneakyButton is not being read as pressed when the joystick is held down and I was wondering how to get around that. I assume multitouch allows that both input be read simultaneously. In my current project, whenever the joystick is held down the character moves in that direction, but i can't seem to press a sneakyinput button while the joystick is held down.
heres my update method for the InputLayer:
GameLayer *game = [GameLayer sharedGameLayer];
Hero* hero =[game getHeroFromLayer];
if (attackButton.active)
{
[hero attack];
}
CGPoint velocity = ccpMult(dPad.velocity, 6500 * dt);
hero.position = ccp(hero.position.x + velocity.x * dt,
hero.position.y + velocity.y * dt);
Sup dude? You should try changing
if (attackButton.active)
to
if (attackButton.value == 1)
Thanks, Gnoob.
After many days struggling with how to concurrently touch on both joystick and attack/jump button but totally failed. Until now I touch this comment, just turn multitouch on, everything works!!!
Change Here:
RootViewController.mm => [eaglView setMultipleTouchEnabled:YES]

Drag sprite in cocos2d for the iPhone - with a max velocity

I'm trying to make a game where the user is supposed to drag a sprite up and down on the screen, avoiding incoming obstacles. The last answer here helped me to drag the sprite around on the screen, but I want to set a maximum speed the sprite can be moved (and hopefully with a natural-looking acceleration/deceleration), so it doesn't get too easy to avoid the objects.
Does anybody know how I can modify the code to achieve this, or is there another way to to it?
Thanks :)
You'll need to maintain a CGPoint destinationPosition variable which is the location of your finger and use an update loop to modify it's position:
-(void) update:(ccTime) dt
{
CGPoint currentPosition = draggableObject.position.x;
if (destination.x != currentPosition.x)
{
currentPosition.x += (destination.x - currentPosition.x) / 5.0f; // This 5.0f is how fast you want the object to move to it's destination
}
if (destination.y != currentPosition.y)
{
currentPosition.y += (destination.y - currentPosition.y) / 5.0f;
}
draggableObject.postion = currentPosition;
}
In the ifs, you might want to check if the objects are close to each other, rather than exactly the same number to allow for rounding errors.
You just need to have an if statement in whatever schedule updater you are using, like time, or touches, or whatever.
I'm presuming you have x/y velocities? Just inside your update statement, wherever your acceleration is -
if(acceleration.x > 20){
acceleration.x = 20;
}
if(acceleration.y > 20){
acceleration.y = 20;
}

Discursive UIAlertView animation while continuous animation?

I'm trying to write a little app, where on the main screen, I animate a flying "bubble". This animation has to be continuous. (I reuse the bubbles, which fly off the screen) I heard that animations have to run on the main thread, as does every operation which changes the UI. Is this true? When I try to show a UIAlertView on this screen, it's animation becomes very discursive because of the continuous bubble animation. (this is a custom alertview with an indicator) The device is an iPhone 4, so I don't think it should be a problem to show a normal UIAlertView.
And I would like to ask if I use the correct method for the bubble animation. So first of all, I use an NSTimer, which invokes the startAnimation method in every 0.01 seconds (I start it in the controller's viewDidAppear: method). In the startAnimation method, at first I generate bubbles with random x and y coordinates (to see bubbles on the screen right after the viewdidappear), and I generate bubbles on the bottom with random x and y = 460 coordinates. In the startAnimation method, I run a counter (called frames), and when the value of this counter equals 35, I call the bubble generate method again.
The problem:
I store the generated bubbles in an array, and the 'gone' bubbles (which are off the screen) in another array. First I try to reuse the bubbles in the gonebubbles array, then if the array is run out, I generate new bubbles. While this operation is processed, the continuous animation stops, then continues. The break is about one second, but this is very disturbing.
Can anyone help in this problem? Thanks in advice, madik
- (void)viewDidAppear {
.
timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:#selector(startAnimation) userInfo:nil repeats:YES];
.
}
- (void)startAnimation {
self.current = [NSDate timeIntervalSinceReferenceDate];
double diff = (self.start - self.current);
if ( diff < 0 ) {
diff = (-1) * diff;
}
self.start = self.current;
frames++;
if ( shouldMoveBubbles ) {
[mug moveBubbles:diff];
}
if ( frames == 35 ) {
DebugLog(#"################################################################");
DebugLog(#"####################### FRAME = 35 ###########################");
DebugLog(#"################################################################");
[mug createNewBubbleOnTheBottomOfView:self.view];
frames = 0;
}
}
In the Mug class:
- (void)moveBubbles:(double)millisElapsed {
for (Bubble *bubble in bubbles) {
int bubbleSpeed = bubble.speed;
float deltaX = (float)(bubbleSpeed * -degrees_sinus * millisElapsed * 100);
float deltaY = (float)(bubbleSpeed * -degrees_cosinus * millisElapsed);
DebugLog(#"movebubbles x: %f, y:%f, speed: %d, sin:%f, cos:%f", deltaX, deltaY, bubbleSpeed, degrees_sinus, degrees_cosinus);
[bubble moveBubbleX:deltaX Y:deltaY];
}
}
And in the Bubble class:
- (void)moveBubbleX:(float)deltaX Y:(float)deltaY {
self.bubbleImage.center = CGPointMake(self.bubbleImage.center.x + deltaX, self.bubbleImage.center.y + deltaY);
}
This sounds like a memory problem. Slow UIAlertView animation is a sure sign of this. It sounds like the way you are generating bubbles is causing the problem. You mentioned the you keep two arrays of bubbles. You never say if you limit the number of bubbles that can be in either array at once. You also don't mention when you clean up these bubbles. It sounds like a memory "black hole". I'd recommend setting a maximum number of bubbles that you can show on screen at once.
Also, you mention a custom alert view. If you're modifying the UIAlertView, you're going to run into problems since that's not officially supported. Additionally, I've seen UIAlertView animation become slow when memory is tight. If you solve the memory issues with your bubbles, you'll probably solve this one too.
Finally, a word of advice. Making an animated game in UIKit is probably not a good idea. NSTimers are not as accurate as many people would like to think. UIImages are relatively expensive to load. Touching moving buttons is known to be unreliable at worst, hackish at best. I suggest looking into a game framework, such as Cocos2d-iphone.
Good luck!

cocos2d moving objects

Im trying to move an object around the screen like in the game geometry wars. I can rotate the object just fine, however I cant seem to get it to move based on the direction it is facing. I have this code here which i think is right for doing this but I keep getting syntax errors:
spriteObject.x = spriteObject.x + speed*cos(Angle)
spriteObject.y = spriteObject.y + speed*sin(Angle)
The errors are 'request for member x not in struct or union.' How do you do this in Objective-c/cocos2d syntax?
Looking at the documentation for the sprite class, you would need to do the following:
float angle = spriteObject.rotation
spriteObject.position.x = spriteObject.position.x + speed*cos(angle)
spriteObject.position.y = spriteObject.position.y + speed*sin(angle)
edit (in response to comment):
I see that you are programming for the iPhone, which means you need to be using the iphone cocos2d library, and not the one I linked to before.
The syntax will be different, as will the example code, since the iPhone version uses the Objective-C langugage, whereas the original cocos2d uses Python.
Google code has good documentation on the iPhone version of cocos2d, including sample code.
Based on that sample code, you will have to do the following:
float newX = spriteObject.position.x + speed * cos(angle);
float newY = spriteObject.position.y + speed * sin(angle);
spriteObject.position = ccp( newX, newY );