Created
April 12, 2012 21:26
-
-
Save quique123/2371083 to your computer and use it in GitHub Desktop.
Chipmunk Collision Detecion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// CPHopper.h | |
// PlanetHopper | |
// | |
// Created by Marcio Valenzuela on 12/29/11. | |
// Copyright (c) 2011 M2Studio. All rights reserved. | |
// | |
#import "CPSprite.h" | |
@interface CPHopper : CPSprite { | |
cpArray *groundShapes; | |
//added to make player jump | |
double jumpStartTime; | |
float accelerationFraction; | |
//track to animate | |
CCAnimation * walkingAnim; | |
CCAnimation * jumpingAnim; | |
CCAnimation * afterJumpingAnim; | |
float lastFlip; | |
//make him jump or fly | |
BOOL jetpack; | |
BOOL hasShield; | |
//Add debuglabel | |
CCLabelBMFont *myDebugLabel; | |
} | |
@property (readonly) cpArray *groundShapes; | |
@property (assign) BOOL jetpack; | |
@property (assign) BOOL hasShield; | |
@property (nonatomic,assign) CCLabelBMFont *myDebugLabel; | |
- (id)initWithLocation:(CGPoint)location space:(cpSpace *)space | |
groundBody:(cpBody *)groundBody; | |
//methods to make ole jump | |
- (void)accelerometer:(UIAccelerometer*)accelerometer | |
didAccelerate:(UIAcceleration*)acceleration; | |
- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event; | |
- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event; | |
-(void)hopperJet2; | |
-(void)setHopperJet; | |
- (void) setDebugLabelTextAndPosition; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// CPHopper.m | |
// PlanetHopper | |
// | |
// Created by Marcio Valenzuela on 12/29/11. | |
// Copyright (c) 2011 M2Studio. All rights reserved. | |
// | |
#import "CPHopper.h" | |
@implementation CPHopper | |
@synthesize groundShapes, jetpack, hasShield; | |
@synthesize myDebugLabel; | |
//methods for collision detec chipmunk | |
static cpBool begin(cpArbiter *arb, cpSpace *space, void *ignore) { | |
CP_ARBITER_GET_SHAPES(arb, hopperShape, groundShape); | |
CPHopper *hopper = (CPHopper *)hopperShape->data; | |
cpVect n = cpArbiterGetNormal(arb, 0); | |
if (n.y < 0.0f) { | |
cpArray *groundShapes = hopper.groundShapes; | |
cpArrayPush(groundShapes, groundShape); | |
} | |
return cpTrue; | |
} | |
//1/4. Testing shield-player gluing together | |
static cpBool beginShield(cpArbiter *arb, cpSpace *space, void *ignore) { | |
CP_ARBITER_GET_SHAPES(arb, hopperShape, shieldShape); | |
NSLog(@"player touched shield"); | |
return cpTrue; | |
} | |
static cpBool preSolve(cpArbiter *arb, cpSpace *space, void *ignore) { | |
if(cpvdot(cpArbiterGetNormal(arb, 0), ccp(0,-1)) < 0){ // 6 | |
return cpFalse; | |
} | |
return cpTrue; | |
} | |
static void separate(cpArbiter *arb, cpSpace *space, void *ignore) { | |
CP_ARBITER_GET_SHAPES(arb, hopperShape, groundShape); // 7 | |
CPHopper *hopper = (CPHopper *)hopperShape->data; | |
cpArrayDeleteObj(hopper.groundShapes, groundShape); | |
} | |
//call animations | |
-(void)initAnimations { | |
walkingAnim = [self loadPlistForAnimationWithName:@"walkingAnim" andClassName:NSStringFromClass([self class])]; | |
[[CCAnimationCache sharedAnimationCache] addAnimation:walkingAnim name:@"walkingAnim"]; | |
//jumpingAnim = [self loadPlistForAnimationWithName:@"jumpingAnim" andClassName:NSStringFromClass([self class])]; | |
//[[CCAnimationCache sharedAnimationCache] addAnimation:jumpingAnim name:@"jumpingAnim"]; | |
//afterJumpingAnim = [self loadPlistForAnimationWithName:@"afterJumpingAnim" andClassName:NSStringFromClass([self class])]; | |
//[[CCAnimationCache sharedAnimationCache] addAnimation:afterJumpingAnim name:@"afterJumpingAnim"]; | |
} | |
//call set up animations | |
-(void)changeState:(CharacterStates)newState { | |
[self stopAllActions]; | |
id action = nil; | |
[self setCharacterState:newState]; | |
switch (newState) { | |
case kStateIdle: | |
[self setDisplayFrame: | |
[[CCSpriteFrameCache sharedSpriteFrameCache] | |
spriteFrameByName:@"70x70mega1.png"]]; | |
break; | |
case kStateWalking: | |
action = [CCAnimate actionWithAnimation:walkingAnim | |
restoreOriginalFrame:NO]; | |
break; | |
/** | |
case kStateJumping: | |
action = [CCAnimate actionWithAnimation:jumpingAnim | |
restoreOriginalFrame:NO]; | |
break; | |
case kStateAfterJumping: | |
action = [CCAnimate actionWithAnimation:afterJumpingAnim | |
restoreOriginalFrame:NO]; | |
//[self playJumpEffect]; | |
break; | |
**/ | |
default: | |
break; | |
} | |
if (action != nil) { | |
[self runAction:action]; | |
} | |
} | |
//draw debug label | |
-(void)setDebugLabelTextAndPosition { | |
CGPoint newPosition = [self position]; | |
NSString *labelString = [NSString stringWithFormat:@"X: %.2f \n Y:%.2f \n", newPosition.x, newPosition.y]; | |
[myDebugLabel setString: [labelString stringByAppendingString:@" tracking..."]]; | |
float yOffset = screenSize.height * 0.195f; | |
newPosition = ccp(newPosition.x,newPosition.y+yOffset); | |
[myDebugLabel setPosition:newPosition]; | |
} | |
//make ole jump | |
-(void)updateStateWithDeltaTime:(ccTime)dt | |
andListOfGameObjects:(CCArray*)listOfGameObjects { | |
//Add for debuglabel | |
[self setDebugLabelTextAndPosition]; | |
//Added to clamp for animation | |
CGPoint oldPosition = self.position; | |
//this is for when ole is in the air | |
[super updateStateWithDeltaTime:dt andListOfGameObjects:listOfGameObjects]; | |
//HOPPER IS IN THE AIR, CONTROL HIS JUMP | |
float jumpFactor; | |
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { | |
jumpFactor = 300.0; | |
} else { | |
jumpFactor = 150.0; | |
} | |
CGPoint newVel = body->v; | |
if (groundShapes->num == 0) { | |
newVel = ccp(jumpFactor*accelerationFraction,body->v.y); | |
} | |
double timeJumping = CACurrentMediaTime()-jumpStartTime; | |
if (jumpStartTime != 0 && timeJumping < 0.25) { | |
newVel.y = jumpFactor*2; | |
} | |
cpBodySetVel(body, newVel); | |
//HOPPER IS ON THE GROUND, CONTROL HIS JUMP (X) | |
if (groundShapes->num > 0) { | |
if (ABS(accelerationFraction) < 0.05) { | |
accelerationFraction = 0; | |
shape->surface_v = ccp(0, 0); | |
} else { | |
float maxSpeed = 200.0f; | |
shape->surface_v = ccp(-maxSpeed*accelerationFraction, 0); | |
cpBodyActivate(body); | |
} | |
} else { | |
shape->surface_v = cpvzero; | |
} | |
//prevent sprite from flying off the sides when in the air | |
float margin = 70; | |
CGSize winSize = [CCDirector sharedDirector].winSize; | |
if (body->p.x < margin) { | |
cpBodySetPos(body, ccp(margin, body->p.y)); | |
} | |
if (body->p.x > winSize.width - margin) { | |
cpBodySetPos(body, ccp(winSize.width - margin, body->p.y)); | |
} | |
// 1. call animations oldPosition | |
if(ABS(accelerationFraction) > 0.05) { | |
double diff = CACurrentMediaTime() - lastFlip; | |
if (diff > 0.1) { | |
lastFlip = CACurrentMediaTime(); | |
if (oldPosition.x > self.position.x) { | |
self.flipX = YES; | |
} else { | |
self.flipX = NO; | |
} | |
} | |
} | |
if (characterState == kStateIdle && accelerationFraction != 0) { | |
[self changeState:kStateWalking]; | |
} | |
if ([self numberOfRunningActions] == 0 && characterState != kStateIdle) { | |
[self changeState:kStateIdle]; | |
} | |
} | |
- (id)initWithLocation:(CGPoint)location space:(cpSpace *)theSpace | |
groundBody:(cpBody *)groundBody { | |
if ((self = [super initWithSpriteFrameName:@"70x70mega1.png"])) { | |
CGSize size; | |
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { | |
size = CGSizeMake(60, 60); | |
self.anchorPoint = ccp(0.5, 30/self.contentSize.height); | |
} else { | |
size = CGSizeMake(30, 30); | |
self.anchorPoint = ccp(0.5, 15/self.contentSize.height); | |
} | |
[self addBoxBodyAndShapeWithLocation:location size:size space:theSpace mass:1.0 e:0.0 u:0.5 collisionType:kCollisionTypeViking canRotate:TRUE]; | |
} | |
//initialize groundarray | |
groundShapes = cpArrayNew(0); | |
cpSpaceAddCollisionHandler(space, kCollisionTypeViking,kCollisionTypeGround, begin, preSolve, NULL, separate, NULL); | |
//2/4. Testing shield-player gluing together | |
//collision detection player-shield | |
//cpSpaceAddCollisionHandler(space, kCollisionTypeViking,kCollisionTypeShield, beginShield, NULL, NULL, NULL, NULL); | |
//add constraint | |
cpConstraint *constraint = cpRotaryLimitJointNew(groundBody, body,CC_DEGREES_TO_RADIANS(-30), CC_DEGREES_TO_RADIANS(30)); | |
cpSpaceAddConstraint(space, constraint); | |
//call animations | |
[self initAnimations]; | |
//set jetpack to false | |
self.jetpack = FALSE; | |
self.hasShield = FALSE; | |
return self; | |
} | |
-(void)setHopperJet{ | |
/* | |
//apply force one-time | |
cpFloat min=900; | |
cpFloat max=915; | |
//cpFloat f=1000; | |
cpFloat f=body->p.y/100; | |
body->f = cpv(0, (cpfclamp(f,min,max))); | |
//cpBodyApplyForce(body, (cpv(0, 1000)),cpvzero);*/ | |
self.jetpack = TRUE; | |
} | |
-(void)setHasShield{ | |
self.hasShield = TRUE; | |
} | |
-(void)hopperJet2{ | |
if(jetpack){ | |
body->f = cpv(0.0, 1000.0*cpfclamp(body->p.y/10.0, 0.0, 1.0)); | |
} else { | |
body->f = cpvzero; | |
} | |
} | |
////CONTROL HOW HOPPER JUMPS | |
- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event { | |
if (jetpack==TRUE) { | |
//run jetpack code | |
NSLog(@"this would be the jetpack true code"); | |
[self hopperJet2]; | |
} else if (groundShapes->num > 0) { | |
NSLog(@"this would be the jetpack false code"); | |
jumpStartTime = CACurrentMediaTime(); | |
} | |
return TRUE; | |
} | |
- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event { | |
if (jetpack==TRUE) { | |
//run jetpack code | |
NSLog(@"this would be the jetpack true code"); | |
cpBodyResetForces(body); | |
} else { | |
NSLog(@"this would be the jetpack false code"); | |
jumpStartTime = 0; | |
} | |
} | |
- (void)accelerometer:(UIAccelerometer*)accelerometer | |
didAccelerate:(UIAcceleration*)acceleration { | |
if (jetpack==TRUE) { | |
//run jetpack code | |
NSLog(@"this would be the jetpack true code"); | |
accelerationFraction = acceleration.y*2; | |
if (accelerationFraction < -1) { | |
accelerationFraction = -1; | |
} else if (accelerationFraction > 1) { | |
accelerationFraction = 1; | |
} | |
if ([[CCDirector sharedDirector] deviceOrientation] == UIDeviceOrientationLandscapeLeft) { | |
accelerationFraction *= -1; | |
} | |
} else { | |
NSLog(@"this would be the jetpack false code"); | |
accelerationFraction = acceleration.y*2; | |
if (accelerationFraction < -1) { | |
accelerationFraction = -1; | |
} else if (accelerationFraction > 1) { | |
accelerationFraction = 1; | |
} | |
if ([[CCDirector sharedDirector] deviceOrientation] == UIDeviceOrientationLandscapeLeft) { | |
accelerationFraction *= -1; | |
} | |
} | |
} | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// CPRayGun.h | |
// PlanetHopper | |
// | |
// Created by Marcio Valenzuela on 1/25/12. | |
// Copyright 2012 M2Studio. All rights reserved. | |
// | |
#import "CPSprite.h" | |
@interface CPShield : CPSprite { | |
cpArray *groundShapes; | |
//added to make player jump | |
double jumpStartTime; | |
float accelerationFraction; | |
//track to animate - left in to be used later to animate power ups-shield | |
CCAnimation * walkingAnim; | |
CCAnimation * jumpingAnim; | |
CCAnimation * afterJumpingAnim; | |
float lastFlip; | |
} | |
@property (readonly) cpArray *groundShapes; | |
- (id)initWithLocation:(CGPoint)location space:(cpSpace *)space | |
groundBody:(cpBody *)groundBody; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// CPRayGun.m | |
// PlanetHopper | |
// | |
// Created by Marcio Valenzuela on 1/25/12. | |
// Copyright 2012 M2Studio. All rights reserved. | |
// | |
#import "CPShield.h" | |
@implementation CPShield | |
@synthesize groundShapes; | |
//Gets collisionObjectTypes from handler in init...and places them in the same order for the begin | |
//Gets vector from groundshape to object. If (-) meaning object is above, it adds groundshape to list of bodies the object is touching | |
static cpBool begin(cpArbiter *arb, cpSpace *space, void *ignore) { | |
CP_ARBITER_GET_SHAPES(arb, hopperShape, groundShape); | |
CPShield *genBod = (CPShield *)hopperShape->data; | |
cpVect n = cpArbiterGetNormal(arb, 0); | |
if (n.y < 0.0f) { | |
cpArray *groundShapes = genBod.groundShapes; | |
cpArrayPush(groundShapes, groundShape); | |
} | |
return cpTrue; | |
} | |
//pre-tests if collision happened with the bottom of the platform & ignores collision...otherwise, continues... | |
static cpBool preSolve(cpArbiter *arb, cpSpace *space, void *ignore) { | |
if(cpvdot(cpArbiterGetNormal(arb, 0), ccp(0,-1)) < 0){ // 6 | |
return cpFalse; | |
} | |
return cpTrue; | |
} | |
//tests if the objects have separated in order to update list of colliding objects... | |
static void separate(cpArbiter *arb, cpSpace *space, void *ignore) { | |
CP_ARBITER_GET_SHAPES(arb, hopperShape, groundShape); // 7 | |
CPShield *genBod = (CPShield *)hopperShape->data; | |
cpArrayDeleteObj(genBod.groundShapes, groundShape); | |
} | |
//call animations | |
-(void)initAnimations { | |
//walkingAnim = [self loadPlistForAnimationWithName:@"walkingAnim" andClassName:NSStringFromClass([self class])]; | |
//[[CCAnimationCache sharedAnimationCache] addAnimation:walkingAnim name:@"walkingAnim"]; | |
//jumpingAnim = [self loadPlistForAnimationWithName:@"jumpingAnim" andClassName:NSStringFromClass([self class])]; | |
//[[CCAnimationCache sharedAnimationCache] addAnimation:jumpingAnim name:@"jumpingAnim"]; | |
//afterJumpingAnim = [self loadPlistForAnimationWithName:@"afterJumpingAnim" andClassName:NSStringFromClass([self class])]; | |
//[[CCAnimationCache sharedAnimationCache] addAnimation:afterJumpingAnim name:@"afterJumpingAnim"]; | |
} | |
//call set up animations | |
-(void)changeState:(CharacterStates)newState { | |
[self stopAllActions]; | |
id action = nil; | |
[self setCharacterState:newState]; | |
switch (newState) { | |
case kStateIdle: | |
[self setDisplayFrame: | |
[[CCSpriteFrameCache sharedSpriteFrameCache] | |
spriteFrameByName:@"shield.png"]]; | |
break; | |
case kStateWalking: | |
action = [CCAnimate actionWithAnimation:walkingAnim | |
restoreOriginalFrame:NO]; | |
break; | |
/** | |
case kStateJumping: | |
action = [CCAnimate actionWithAnimation:jumpingAnim | |
restoreOriginalFrame:NO]; | |
break; | |
case kStateAfterJumping: | |
action = [CCAnimate actionWithAnimation:afterJumpingAnim | |
restoreOriginalFrame:NO]; | |
//[self playJumpEffect]; | |
break; | |
**/ | |
default: | |
break; | |
} | |
if (action != nil) { | |
[self runAction:action]; | |
} | |
} | |
//make player jump | |
-(void)updateStateWithDeltaTime:(ccTime)dt | |
andListOfGameObjects:(CCArray*)listOfGameObjects { | |
CGPoint oldPosition = self.position;//added to clamp for animation | |
//this is for when ole is in the air | |
[super updateStateWithDeltaTime:dt andListOfGameObjects:listOfGameObjects]; | |
float jumpFactor; | |
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { | |
jumpFactor = 300.0; | |
} else { | |
jumpFactor = 150.0; | |
} | |
CGPoint newVel = body->v; | |
if (groundShapes->num == 0) { | |
newVel = ccp(jumpFactor*accelerationFraction,body->v.y); | |
} | |
double timeJumping = CACurrentMediaTime()-jumpStartTime; | |
if (jumpStartTime != 0 && timeJumping < 0.25) { | |
newVel.y = jumpFactor*2; | |
} | |
cpBodySetVel(body, newVel); | |
//this is for when ole is on the ground | |
if (groundShapes->num > 0) { | |
if (ABS(accelerationFraction) < 0.05) { | |
accelerationFraction = 0; | |
shape->surface_v = ccp(0, 0); | |
} else { | |
float maxSpeed = 200.0f; | |
shape->surface_v = ccp(-maxSpeed*accelerationFraction, 0); | |
cpBodyActivate(body); | |
} | |
} else { | |
shape->surface_v = cpvzero; | |
} | |
//prevent sprite from flying off the sides when in the air | |
float margin = 70; | |
CGSize winSize = [CCDirector sharedDirector].winSize; | |
if (body->p.x < margin) { | |
cpBodySetPos(body, ccp(margin, body->p.y)); | |
} | |
if (body->p.x > winSize.width - margin) { | |
cpBodySetPos(body, ccp(winSize.width - margin, body->p.y)); | |
} | |
//animate hopper | |
// 1. call animations oldPosition | |
if(ABS(accelerationFraction) > 0.05) { | |
double diff = CACurrentMediaTime() - lastFlip; | |
if (diff > 0.1) { | |
lastFlip = CACurrentMediaTime(); | |
if (oldPosition.x > self.position.x) { | |
self.flipX = YES; | |
} else { | |
self.flipX = NO; | |
} | |
} | |
} | |
if (characterState == kStateIdle && accelerationFraction != 0) { | |
[self changeState:kStateWalking]; | |
} | |
if ([self numberOfRunningActions] == 0 && characterState != kStateIdle) { | |
[self changeState:kStateIdle]; | |
} | |
} | |
- (id)initWithLocation:(CGPoint)location space:(cpSpace *)theSpace | |
groundBody:(cpBody *)groundBody { | |
if ((self = [super initWithSpriteFrameName:@"shield.png"])) { | |
CGSize size; | |
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { | |
size = CGSizeMake(60, 60); | |
self.anchorPoint = ccp(0.5, 30/self.contentSize.height); | |
} else { | |
size = CGSizeMake(30, 30); | |
self.anchorPoint = ccp(0.5, 15/self.contentSize.height); | |
} | |
[self addBoxBodyAndShapeWithLocation:location | |
size:size space:theSpace mass:1.0 e:0.0 u:0.5 | |
collisionType:kCollisionTypeShield canRotate:TRUE]; | |
} | |
//flip enemy | |
self.flipX = YES; | |
//initialize groundarray | |
groundShapes = cpArrayNew(0); | |
cpSpaceAddCollisionHandler(space, kCollisionTypeViking,kCollisionTypeGround, begin, preSolve, NULL, separate, NULL); | |
//add constraint | |
cpConstraint *constraint = cpRotaryLimitJointNew(groundBody, body, CC_DEGREES_TO_RADIANS(-30), CC_DEGREES_TO_RADIANS(30)); | |
cpSpaceAddConstraint(space, constraint); | |
//call animations | |
[self initAnimations]; | |
return self; | |
} | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Scene1ActionLayer.h | |
// PlanetHopper | |
// | |
// Created by Marcio Valenzuela on 12/13/11. | |
// Copyright 2011 M2Studio. All rights reserved. | |
// | |
#import <Foundation/Foundation.h> | |
#import "cocos2d.h" | |
#import "chipmunk.h" | |
#import "cpMouse.h" | |
#import "drawSpace.h" | |
#import "GameObject.h" | |
@class Scene1BackgroundLayer; | |
@class CPHopper; //hopper | |
@class CPGenericBody; //jj1 | |
@class CPGenericPowerUp; //enemyRobot--mega2 | |
@class Jetpack; | |
@class CPFlower; //flower | |
@class CPShip; //ship | |
@class CPShield; | |
@interface Scene1ActionLayer : CCLayer { | |
Scene1BackgroundLayer * uiLayer; | |
double startTime; | |
//chipmunk | |
cpSpace *space; | |
cpBody *groundBody; | |
cpMouse *mouse; | |
//add CPViking | |
CPHopper *hopper; | |
CCSpriteBatchNode *sceneSpriteBatchNode; | |
//add genericbody-enemyrobot | |
CPGenericBody *genericBody; //jj1 | |
CPFlower *flowerBody; //flower | |
CPShip *ship; //ship | |
CPGenericPowerUp *enemyRobot; //enemyRobot--mega2 | |
CPShield *shield; //shield | |
//fire & smoke | |
CCParticleSystem *fireOnBridge; | |
//smoke | |
CCParticleSystem *smokeParticleSystem; | |
//debuglabel | |
//CCLabelBMFont *debugLabel; | |
CCLabelTTF *platformDebugLabel; | |
} | |
- (id)initWithScene1BackgroundLayer:(Scene1BackgroundLayer *)scene5UILayer; | |
-(void)createObjectOfType:(GameObjectType)objectType withHealth:(int)initialHealth atLocation:(CGPoint)spawnLocation withZValue:(int)ZValue; | |
-(void)createJetpack; | |
-(void)createParticleSystemAndRun; | |
-(void)randomizeSmoke:(ccTime) dt; | |
-(void)createParticleSystem; | |
- (void)startFire; | |
-(void)addLabel; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Scene1ActionLayer.m | |
// PlanetHopper | |
// | |
// Created by Marcio Valenzuela on 12/13/11. | |
// Copyright 2011 M2Studio. All rights reserved. | |
// | |
#import "Scene1ActionLayer.h" | |
#import "Scene1BackgroundLayer.h" | |
#import "CPHopper.h" //main char | |
#import "CPGenericBody.h" // enemy robot | |
#import "CPGenericPowerUp.h" // jetpack powerup | |
#import "JetPack.h" | |
#import "CPFlower.h" // flower powerup | |
#import "CPShip.h" // ship powerup | |
#import "CPShield.h" | |
#import "Constants.h" | |
#import "CommonProtocols.h" | |
#import "CPRevolvePlatform.h" | |
#import "CPPivotPlatform.h" | |
#import "CPSpringPlatform.h" | |
#import "CPNormalPlatform.h" | |
#import "GameManager.h" | |
@implementation Scene1ActionLayer | |
- (void)createSpace { | |
space = cpSpaceNew(); // 1 | |
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { | |
space->gravity = ccp(0, -1500); // 2 | |
} else { | |
space->gravity = ccp(0, -750); | |
} | |
cpSpaceResizeStaticHash(space, 400, 200); // 3 | |
cpSpaceResizeActiveHash(space, 200, 200); | |
} | |
- (void)createBoxAtLocation:(CGPoint)location { | |
cpFloat hw, hh; | |
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { | |
hw = 100.0/2.0f; | |
hh = 10.0/2.0f; | |
} else { | |
hw = 50.0/2.0f; | |
hh = 5.0/2.0f; | |
} | |
cpVect verts[] = { | |
cpv(-hw,-hh), | |
cpv(-hw, hh), | |
cpv( hw, hh), | |
cpv( hw,-hh), | |
}; | |
cpShape *shape = cpPolyShapeNew(groundBody, 4, verts, location); | |
shape->e = 1.0; | |
shape->u = 1.0; | |
shape->collision_type = kCollisionTypeGround; | |
cpSpaceAddShape(space, shape); | |
} | |
//add platforms | |
- (void)createRevolvePlatformAtLocation:(CGPoint)location { | |
CPRevolvePlatform *revolvePlatform = [[[CPRevolvePlatform alloc] initWithLocation:location space:space groundBody:groundBody] autorelease]; | |
[sceneSpriteBatchNode addChild:revolvePlatform]; | |
} | |
- (void)createPivotPlatformAtLocation:(CGPoint)location { | |
CPPivotPlatform *pivotPlatform = [[[CPPivotPlatform alloc] | |
initWithLocation:location space:space groundBody:groundBody] | |
autorelease]; | |
[sceneSpriteBatchNode addChild:pivotPlatform]; | |
} | |
- (void)createSpringPlatformAtLocation:(CGPoint)location { | |
CPSpringPlatform *springPlatform = [[[CPSpringPlatform alloc] | |
initWithLocation:location space:space groundBody:groundBody] | |
autorelease]; | |
[sceneSpriteBatchNode addChild:springPlatform]; | |
} | |
- (void)createNormalPlatformAtLocation:(CGPoint)location { | |
CPNormalPlatform *normPlatform = [[[CPNormalPlatform alloc] initWithLocation:location space:space groundBody:groundBody] autorelease]; | |
[sceneSpriteBatchNode addChild:normPlatform]; | |
NSString *labelString = [NSString stringWithFormat:@"%.2f-%.2f", normPlatform.position.x, normPlatform.position.y]; | |
platformDebugLabel = [CCLabelTTF labelWithString:labelString fontName:@"Arial" fontSize:16]; | |
//[CCLabelBMFont labelWithString:@"hello" fntFile:@"Arial.fnt" fontSize:8]; | |
platformDebugLabel.position = ccp(normPlatform.position.x, normPlatform.position.y); | |
[self addChild:platformDebugLabel]; | |
} | |
//central game logic | |
- (void)createLevel { | |
CGSize winSize = [CCDirector sharedDirector].winSize; | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.2, winSize.height * 0.15)];//A-------BEGIN 1ST SCREENFUL | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.4, winSize.height * 0.30)];//B | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.65, winSize.height * 0.45)];//C | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.4, winSize.height * 0.55)];//D | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.2, winSize.height * 0.75)];//E -- FORK | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.4, winSize.height * 0.95)];//F1 | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.05, winSize.height * 0.95)];//F2 -- TOO HIGH PATH | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.55, winSize.height * 1.15)];//G1 | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.2, winSize.height * 1.25)];//G2 -- TOO HIGH PATH | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.85, winSize.height * 1.25)];//H1 | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.6, winSize.height * 1.45)];//I1 | |
//[self createPivotPlatformAtLocation:ccp(winSize.width * 0.4, winSize.height * 1.65)];//J1 | |
[self createPivotPlatformAtLocation:ccp(winSize.width * 0.4, winSize.height * 1.85)];//K1 | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.2, winSize.height * 2.15)];//-------BEGIN 2ND SCREENFUL | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.75, winSize.height * 2.15)]; | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.50, winSize.height * 2.35)];//CENTER START | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.2, winSize.height * 2.55)]; | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.75, winSize.height * 2.55)]; | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.05, winSize.height * 2.75)]; | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.85, winSize.height * 2.75)]; | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.2, winSize.height * 2.95)]; | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.75, winSize.height * 2.95)]; | |
[self createPivotPlatformAtLocation:ccp(winSize.width * 0.50, winSize.height * 3.15)];//CENTER FINAL | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.75, winSize.height * 3.35)];//OFF TO THE LEFT | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.95, winSize.height * 3.55)]; | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.75, winSize.height * 3.75)]; | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.55, winSize.height * 3.95)]; | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.55, winSize.height * 4.05)];//-------BEGIN 3RD SCREENFUL | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.75, winSize.height * 4.25)]; | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.95, winSize.height * 4.45)]; | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.80, winSize.height * 4.65)]; | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.95, winSize.height * 4.85)]; | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.80, winSize.height * 5.05)]; | |
[self createSpringPlatformAtLocation:ccp(winSize.width * 0.25, winSize.height * 5.05)];//SHOULD FALL DOWN | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.75, winSize.height * 5.25)]; | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.55, winSize.height * 5.45)]; | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.35, winSize.height * 5.65)]; | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.15, winSize.height * 5.85)]; | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.35, winSize.height * 6.05)]; | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.35, winSize.height * 6.25)];//-------BEGIN 4TH SCREENFUL | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.40, winSize.height * 6.45)]; | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.50, winSize.height * 6.65)]; | |
[self createSpringPlatformAtLocation:ccp(winSize.width * 0.25, winSize.height * 6.55)];//SHOOTS UP TOWARDS TOP | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.30, winSize.height * 6.95)]; | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.55, winSize.height * 7.15)]; | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.35, winSize.height * 7.35)];//UNREACHABLE POWERUP | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.60, winSize.height * 7.55)]; | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.80, winSize.height * 7.75)]; | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.65, winSize.height * 7.95)]; | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.90, winSize.height * 8.05)]; | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.99, winSize.height * 8.25)]; | |
/** | |
[self createRevolvePlatformAtLocation:ccp(winSize.width * 0.5, winSize.height * 3.50)]; | |
[self createNormalPlatformAtLocation:ccp(winSize.width * 0.8, winSize.height * 3.65)]; | |
**/ | |
} | |
- (void)createGround { | |
// 1 | |
CGSize winSize = [CCDirector sharedDirector].winSize; | |
CGPoint lowerLeft = ccp(0, 0); | |
CGPoint lowerRight = ccp(winSize.width, 0); | |
groundBody = cpBodyNewStatic(); // 2 | |
float radius = 10.0f; | |
cpShape * shape = cpSegmentShapeNew(groundBody, | |
lowerLeft, lowerRight, radius); // 3 | |
shape->e = 1.0f; // 4 | |
shape->u = 1.0f; // 5 | |
shape->layers ^= GRABABLE_MASK_BIT; // 6 | |
shape->collision_type = kCollisionTypeGround; // added chipmunk for collision type | |
cpSpaceAddShape(space, shape); // 7 | |
} | |
- (void)createBackground { | |
CCParallaxNode * parallax = [CCParallaxNode node]; | |
[CCTexture2D setDefaultAlphaPixelFormat:kCCTexture2DPixelFormat_RGB565]; | |
CCSprite *background; | |
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { | |
background = [CCSprite spriteWithFile:@"chipmunk_background-ipad.png"]; | |
} else { | |
background = [CCSprite spriteWithFile:@"chipmunk_background.png"]; | |
} | |
background.anchorPoint = ccp(0,0); | |
[CCTexture2D setDefaultAlphaPixelFormat:kCCTexture2DPixelFormat_Default]; | |
[parallax addChild:background z:-10 parallaxRatio:ccp(0.1f, 0.1f) positionOffset:ccp(0,0)]; | |
[self addChild:parallax z:-10]; | |
CCSprite *groundSprite; | |
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { | |
groundSprite = [CCSprite spriteWithFile:@"chipmunk_ground-hd.png"]; | |
} else { | |
groundSprite = [CCSprite spriteWithFile:@"chipmunk_ground.png"]; | |
} | |
groundSprite.anchorPoint = ccp(0,0); | |
groundSprite.position = ccp(0,0); | |
[self addChild:groundSprite z:-10]; | |
[background runAction: | |
[CCRepeatForever actionWithAction: | |
[CCSequence actions: | |
[CCTintTo actionWithDuration:0.5 red:200 green:0 blue:0], | |
[CCTintTo actionWithDuration:0.5 red:255 green:255 blue:255], | |
nil]]]; | |
} | |
- (void)followPlayer:(ccTime)dt { | |
static double totalTime = 0; | |
totalTime += dt; | |
double shakesPerSecond = 5; | |
double shakeOffset = 3; | |
double shakeX = sin(totalTime*M_PI*2*shakesPerSecond) * shakeOffset; | |
CGSize winSize = [CCDirector sharedDirector].winSize; | |
float fixedPosition = winSize.height/4; | |
float newY = fixedPosition - hopper.position.y; | |
float groundMaxY = 4048;//THIS SETS THE HEIGHT OF THIS SCENE | |
newY = MIN(newY, 50); | |
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) { | |
groundMaxY = 3000;//THIS SETS THE HEIGHT OF THIS SCENE | |
newY = MIN(newY, 25); | |
} | |
newY = MAX(newY, -groundMaxY-fixedPosition); | |
CGPoint newPos = ccp(shakeX, newY); | |
[self setPosition:newPos]; | |
} | |
// init & update | |
- (id)initWithScene1BackgroundLayer:(Scene1BackgroundLayer *)scene5UILayer { | |
if ((self = [super init])) { | |
uiLayer = scene5UILayer; | |
startTime = CACurrentMediaTime(); | |
[self scheduleUpdate]; | |
self.isAccelerometerEnabled = YES; | |
//chipmunk | |
[self createSpace]; | |
[self createGround]; | |
mouse = cpMouseNew(space); | |
self.isTouchEnabled = YES; | |
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { | |
[[CCSpriteFrameCache sharedSpriteFrameCache] | |
addSpriteFramesWithFile:@"escapesceneatlas.plist"]; | |
sceneSpriteBatchNode = [CCSpriteBatchNode | |
batchNodeWithFile:@"escapesceneatlas.png"]; | |
//add the batchnode to layer | |
[self addChild:sceneSpriteBatchNode z:0]; | |
hopper = [[[CPHopper alloc] initWithLocation:ccp(200,200) space:space groundBody:groundBody] autorelease]; | |
} else { | |
[[CCSpriteFrameCache sharedSpriteFrameCache] | |
addSpriteFramesWithFile:@"escapesceneatlas.plist"]; | |
sceneSpriteBatchNode = [CCSpriteBatchNode | |
batchNodeWithFile:@"escapesceneatlas.png"]; | |
//add the batchnode to layer | |
[self addChild:sceneSpriteBatchNode z:0]; | |
//Viking became hopper and starts at bottom | |
hopper = [[[CPHopper alloc] initWithLocation:ccp(100,100) space:space groundBody:groundBody] autorelease]; | |
//An enemy robot | |
genericBody = [[[CPGenericBody alloc] initWithLocation:ccp(400,450) space:space groundBody:groundBody] autorelease]; | |
//The flower required to save the planet | |
flowerBody = [[[CPFlower alloc] initWithLocation:ccp(140,900) space:space groundBody:groundBody] autorelease]; | |
//The enemyRobot--mega2 | |
enemyRobot = [[[CPGenericPowerUp alloc] initWithLocation:ccp(450,500) space:space groundBody:groundBody] autorelease]; | |
//The escape ship | |
ship = [[[CPShip alloc] initWithLocation:ccp(400,3200) space:space groundBody:groundBody] autorelease]; | |
//4/4. Testing shield-player gluing together | |
//The raygun | |
//shield = [[[CPShield alloc] initWithLocation:ccp(100,800) space:space groundBody:groundBody] autorelease]; | |
} | |
[self addLabel]; | |
[sceneSpriteBatchNode addChild:hopper z:2]; | |
[sceneSpriteBatchNode addChild:genericBody z:2]; | |
[sceneSpriteBatchNode addChild:enemyRobot z:2]; | |
[sceneSpriteBatchNode addChild:flowerBody z:2]; | |
[sceneSpriteBatchNode addChild:ship z:2]; | |
//3/4. Testing shield-player gluing together | |
[sceneSpriteBatchNode addChild:shield z:2]; | |
[self createLevel]; | |
//schedule a timer to drop jetpack | |
//drop jetpack after reaching a certain height | |
//[self schedule:@selector(createJetpack) interval:1.0]; | |
// better way to createJetpack by delay instead of calling update every 30 secs | |
id action1 = [CCDelayTime actionWithDuration:1.0f]; | |
id action2 = [CCCallFuncN actionWithTarget:self selector:@selector(createJetpack)]; | |
id action3 =[CCSequence actions:action1,action2,nil]; | |
[self runAction:action3]; | |
} | |
//start fire & smoke | |
[self createParticleSystem]; | |
[self createParticleSystemAndRun]; | |
return self; | |
} | |
-(void)addLabel{ | |
//set debuglabel | |
CCLabelBMFont *debugLabel=[CCLabelBMFont labelWithString:@"NoneNone" fntFile:@"SpaceVikingFont.fnt"]; | |
[self addChild:debugLabel]; | |
[hopper setMyDebugLabel:debugLabel]; | |
} | |
-(void)createJetpack{ | |
//Create fire | |
[self startFire]; | |
//Create Jetpack | |
NSLog(@"createJetpack called..."); | |
[self createObjectOfType:kPowerUpTypeJetpack withHealth:100 atLocation:ccp(100,2150) withZValue:500]; | |
//Need to add collision detection in update to determine if touched jetpack...if TRUE then call setHopperJet | |
[hopper setHopperJet]; | |
} | |
- (void)update:(ccTime)dt { | |
static double MAX_TIME = 60; | |
double timeSoFar = CACurrentMediaTime() - startTime; | |
double remainingTime = MAX_TIME - timeSoFar; | |
[uiLayer displaySecs:remainingTime]; | |
static double UPDATE_INTERVAL = 1.0f/60.0f; | |
static double MAX_CYCLES_PER_FRAME = 5; | |
static double timeAccumulator = 0; | |
timeAccumulator += dt; | |
if (timeAccumulator > (MAX_CYCLES_PER_FRAME * UPDATE_INTERVAL)) { | |
timeAccumulator = UPDATE_INTERVAL; | |
} | |
while (timeAccumulator >= UPDATE_INTERVAL) { | |
timeAccumulator -= UPDATE_INTERVAL; | |
cpSpaceStep(space, UPDATE_INTERVAL); | |
} | |
//CPViking- calls the update method of gameobject's CPSprite...telling its sprites to update their position... | |
CCArray *listOfGameObjects = [sceneSpriteBatchNode children]; | |
for (GameCharacter *tempChar in listOfGameObjects) { | |
[tempChar updateStateWithDeltaTime:dt | |
andListOfGameObjects:listOfGameObjects]; | |
} | |
//call follow player | |
[self followPlayer:dt]; | |
//Check for collision between hopper & jetpack | |
//Check for collision between hopper & shield | |
//Check for collision between hopper & phaser | |
//check for win/lose | |
if (remainingTime <= 0) { | |
[[GameManager sharedGameManager] setHasPlayerDied:YES]; | |
[[GameManager sharedGameManager] runSceneWithID:kLevelCompleteScene]; | |
} else if (hopper.position.y > 2500) { | |
[[GameManager sharedGameManager] setHasPlayerDied:NO]; | |
[[GameManager sharedGameManager] runSceneWithID:kLevelCompleteScene]; | |
} | |
} | |
//objects to be dropped in | |
#pragma mark - | |
-(void)createObjectOfType:(GameObjectType)objectType withHealth:(int)initialHealth atLocation:(CGPoint)spawnLocation withZValue:(int)ZValue { | |
if (kPowerUpTypeJetpack == objectType) { | |
CCLOG(@"GameplayLayer -> Creating mallet powerup"); | |
JetPack *jetpack2 = [[JetPack alloc] initWithSpriteFrameName:@"jetpack.png"]; | |
[jetpack2 setPosition:spawnLocation]; | |
[sceneSpriteBatchNode addChild:jetpack2 z:ZValue]; | |
[jetpack2 release]; | |
} else if (kPowerUpTypeHealth == objectType) { | |
/*CCLOG(@"GameplayLayer-> Creating Health Powerup"); | |
Health *health = | |
[[Health alloc] initWithSpriteFrameName:@"sandwich_1.png"]; | |
[health setPosition:spawnLocation]; | |
[sceneSpriteBatchNode addChild:health]; | |
[health release]; | |
*/ | |
} | |
} | |
//fire & smoke | |
-(void)createParticleSystemAndRun{ | |
//ADD PARTICLE SYSTEM | |
// Add Snow Particle System | |
smokeParticleSystem = [CCParticleSmoke node]; | |
[self addChild:smokeParticleSystem]; | |
smokeParticleSystem.position = ccp(240, 40); | |
[self schedule:@selector(randomizeSmoke:) interval:0.5]; | |
} | |
-(void)randomizeSmoke:(ccTime) dt{ | |
if (smokeParticleSystem.position.x < 460 && smokeParticleSystem.position.x > 0) { | |
int incrX = smokeParticleSystem.position.x + 50; | |
int incrY = smokeParticleSystem.position.y + 50; | |
smokeParticleSystem.position = ccp(incrX, incrY); | |
} else { | |
int incrX = smokeParticleSystem.position.x - 50; | |
int incrY = smokeParticleSystem.position.y - 50; | |
smokeParticleSystem.position = ccp(incrX, incrY); | |
} | |
//NSLog(@"hi"); | |
} | |
//add fire & smoke | |
- (void)createParticleSystem { | |
fireOnBridge = [CCParticleSystemQuad | |
particleWithFile:@"fire.plist"]; | |
fireOnBridge.position = ccp(20, 80); | |
[fireOnBridge stopSystem]; | |
[self addChild:fireOnBridge z:10]; | |
} | |
- (void)startFire { | |
//PLAYSOUNDEFFECT(FLAME_SOUND); | |
[fireOnBridge resetSystem]; | |
} | |
//chipmunk debugdraw method | |
- (void)draw { | |
drawSpaceOptions options = { | |
0, // drawHash | |
0, // drawBBs | |
1, // drawShapes | |
4.0f, // collisionPointSize | |
0.0f, // bodyPointSize | |
1.5f, // lineThickness | |
}; | |
drawSpace(space, &options); | |
} | |
- (void)registerWithTouchDispatcher { | |
[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self | |
priority:0 swallowsTouches:YES]; | |
} | |
- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event { | |
[hopper ccTouchBegan:touch withEvent:event]; | |
return YES; | |
} | |
- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event { | |
[hopper ccTouchEnded:touch withEvent:event]; | |
} | |
- (void)accelerometer:(UIAccelerometer *)accelerometer | |
didAccelerate:(UIAcceleration *)acceleration { | |
[hopper accelerometer:accelerometer didAccelerate:acceleration]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment