Created
December 7, 2012 01:03
-
-
Save quique123/4229884 to your computer and use it in GitHub Desktop.
Santiboy
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
// | |
// Puzzle2Layer.m | |
// iSanti | |
// | |
// Created by Marcio Valenzuela on 1/19/12. | |
// Copyright 2012 M2Studio. All rights reserved. | |
// | |
#import "Puzzle2Layer.h" | |
#import "SimpleQueryCallback.h" | |
//#import "Box2DSprite.h" | |
#import "GameManager.h" | |
#import "SimpleAudioEngine.h" | |
//#import "BoxDebugLayer.h" | |
@implementation Puzzle2Layer | |
//SCROLLING BACKGROUNDS | |
// Scrolling with just a large width *2 background | |
-(void)addScrollingBackground { | |
CGSize screenSize = [[CCDirector sharedDirector] winSize]; | |
CGSize levelSize = [[GameManager sharedGameManager] getDimensionsOfCurrentScene]; | |
CCSprite *scrollingBackground; | |
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { | |
// Indicates game is running on iPad | |
scrollingBackground = | |
[CCSprite spriteWithFile:@"FlatScrollingLayer.png"]; | |
} else { | |
scrollingBackground = | |
[CCSprite spriteWithFile:@"FlatScrollingLayeriPhone.png"]; | |
} | |
[scrollingBackground setPosition:ccp(levelSize.width/2.0f,screenSize.height/2.0f)]; | |
[self addChild:scrollingBackground z:0]; | |
} | |
// Scrolling with 3 Parallax backgrounds | |
-(void)addScrollingBackgroundWithParallax { | |
CGSize screenSize = [[CCDirector sharedDirector] winSize]; | |
CGSize levelSize = [[GameManager sharedGameManager] | |
getDimensionsOfCurrentScene]; | |
CCSprite *BGLayer1; | |
CCSprite *BGLayer2; | |
CCSprite *BGLayer3; | |
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { | |
// Indicates game is running on iPad | |
BGLayer1 = [CCSprite spriteWithFile:@"chap9_scrolling4.png"]; | |
BGLayer2 = [CCSprite spriteWithFile:@"chap9_scrolling2.png"]; | |
BGLayer3 = [CCSprite spriteWithFile:@"chap9_scrolling3.png"]; | |
} else { | |
BGLayer1 = [CCSprite spriteWithFile:@"chap9_scrolling4iPhone.png"]; | |
BGLayer2 = [CCSprite spriteWithFile:@"chap9_scrolling2iPhone.png"]; | |
BGLayer3 = [CCSprite spriteWithFile:@"chap9_scrolling3iPhone.png"]; | |
} | |
// chap9_scrolling4 is the ground | |
// chap9_scrolling2 are the large mountains | |
// chap9_scrolling3 are the small rocks | |
parallaxNode = [CCParallaxNode node]; | |
[parallaxNode setPosition:ccp(levelSize.width/2.0f,screenSize.height/2.0f)]; | |
float xOffset = 0; | |
// Ground moves at ratio 1,1 | |
[parallaxNode addChild:BGLayer1 z:1 parallaxRatio:ccp(1.0f,1.0f) positionOffset:ccp(0.0f,0.0f)]; | |
xOffset = (levelSize.width/2) * 0.3f; | |
[parallaxNode addChild:BGLayer2 z:1 parallaxRatio:ccp(0.2f,1.0f) positionOffset:ccp(xOffset, 0)]; | |
xOffset = (levelSize.width/2) * 0.8f; | |
[parallaxNode addChild:BGLayer3 z:1 parallaxRatio:ccp(0.7f,1.0f) positionOffset:ccp(xOffset, 0)]; | |
[self addChild:parallaxNode z:1]; | |
} | |
// Scrolling with TileMap Layers inside of a Parallax Node | |
-(void)addScrollingBackgroundWithTileMapInsideParallax { | |
CGSize screenSize = [[CCDirector sharedDirector] winSize]; | |
CGSize levelSize = [[GameManager sharedGameManager] getDimensionsOfCurrentScene]; | |
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { | |
tileMapNode = [CCTMXTiledMap tiledMapWithTMXFile:@"Level2TileMap.tmx"]; | |
NSLog(@"ipad in addScrolling..."); | |
} else { | |
tileMapNode = [CCTMXTiledMap tiledMapWithTMXFile:@"Level2TileMapiPhone.tmx"]; | |
NSLog(@"iphone in addScrolling..."); | |
} | |
CCTMXLayer *groundLayer = [tileMapNode layerNamed:@"GroundLayer"]; | |
CCTMXLayer *rockColumnsLayer = [tileMapNode layerNamed:@"RockColumnsLayer"]; | |
CCTMXLayer *rockBoulderLayer = [tileMapNode layerNamed:@"RockBoulderLayer"]; | |
parallaxNode = [CCParallaxNode node]; | |
[parallaxNode setPosition:ccp(levelSize.width/2,screenSize.height/2)]; | |
float xOffset = 0.0f; | |
xOffset = (levelSize.width/2); | |
[groundLayer retain]; | |
[groundLayer removeFromParentAndCleanup:NO]; | |
[groundLayer setAnchorPoint:CGPointMake(0.5f, 0.5f)]; | |
[parallaxNode addChild:groundLayer z:30 parallaxRatio:ccp(1,1) positionOffset:ccp(0,0)]; | |
[groundLayer release]; | |
xOffset = (levelSize.width/2) * 0.8f; | |
[rockColumnsLayer retain]; | |
[rockColumnsLayer removeFromParentAndCleanup:NO]; | |
[rockColumnsLayer setAnchorPoint:CGPointMake(0.5f, 0.5f)]; | |
[parallaxNode addChild:rockColumnsLayer z:20 parallaxRatio:ccp(0.2,1) positionOffset:ccp(xOffset, 0.0f)]; | |
[rockColumnsLayer release]; | |
xOffset = (levelSize.width/2) * 0.3f; | |
[rockBoulderLayer retain]; | |
[rockBoulderLayer removeFromParentAndCleanup:NO]; | |
[rockBoulderLayer setAnchorPoint:CGPointMake(0.5f, 0.5f)]; | |
[parallaxNode addChild:rockBoulderLayer z:30 parallaxRatio:ccp(0.7,1) positionOffset:ccp(xOffset, 0.0f)]; | |
[rockBoulderLayer release]; | |
[self addChild:parallaxNode z:1]; | |
} | |
-(void)dealloc { | |
if (world) { | |
delete world; | |
world = NULL; | |
} | |
if (debugDraw) { | |
delete debugDraw; | |
debugDraw = nil; | |
} | |
[super dealloc]; | |
} | |
-(void)setupWorld { | |
b2Vec2 gravity = b2Vec2(0.0f, -4.0f); | |
bool doSleep = true; | |
world = new b2World(gravity, doSleep); | |
} | |
-(void)createBoxAtLocation:(CGPoint)location withSize:(CGSize)size friction:(float32)friction restitution:(float32)restitution density:(float32)density { | |
// define the body | |
b2BodyDef bodyDef; | |
bodyDef.type = b2_dynamicBody; | |
bodyDef.position = b2Vec2(location.x/PTM_RATIO, location.y/PTM_RATIO); | |
//create the body | |
b2Body *body = world->CreateBody(&bodyDef); | |
// define the fixture | |
b2PolygonShape shape; | |
shape.SetAsBox(size.width/2/PTM_RATIO, size.height/2/PTM_RATIO); | |
b2FixtureDef fixtureDef; | |
fixtureDef.shape = &shape; | |
fixtureDef.density = 1.0; | |
fixtureDef.density = density; | |
fixtureDef.friction = friction; | |
fixtureDef.restitution = restitution; | |
//create the fixture | |
body->CreateFixture(&fixtureDef); | |
} | |
-(void)createBodyAtLocation:(CGPoint)location forSprite:(Box2DSprite *)sprite friction:(float32)friction restitution:(float32)restitution density:(float32)density isBox:(BOOL)isBox { | |
b2BodyDef bodyDef; | |
bodyDef.type = b2_dynamicBody; | |
bodyDef.position = b2Vec2(location.x/PTM_RATIO, | |
location.y/PTM_RATIO); | |
bodyDef.allowSleep = false; | |
b2Body *body = world->CreateBody(&bodyDef); | |
body->SetUserData(sprite); | |
sprite.body = body; | |
b2FixtureDef fixtureDef; | |
if (isBox) { | |
b2PolygonShape shape; | |
shape.SetAsBox(sprite.contentSize.width/2/PTM_RATIO, | |
sprite.contentSize.height/2/PTM_RATIO); | |
fixtureDef.shape = &shape; | |
} else { | |
b2CircleShape shape; | |
shape.m_radius = sprite.contentSize.width/2/PTM_RATIO; | |
fixtureDef.shape = &shape; | |
} | |
fixtureDef.density = density; | |
fixtureDef.friction = friction; | |
fixtureDef.restitution = restitution; | |
body->CreateFixture(&fixtureDef); | |
} | |
-(void)createSantiBoyAtLocation:(CGPoint)location { | |
santi = [SantiBoy node]; | |
[self createBodyAtLocation:location forSprite:santi friction:0.5 restitution:0.2 density:1.0 isBox:TRUE]; | |
[sceneSpriteBatchNode addChild:santi z:2 tag:kVikingSpriteTagValue]; | |
santiB2Body = santi.body; | |
} | |
/** | |
-(void)setupDebugDraw { | |
//debugDraw = new GLESDebugDraw(PTM_RATIO *[[CCDirector sharedDirector] contentScaleFactor]); | |
debugDraw = new GLESDebugDraw(); | |
world->SetDebugDraw(debugDraw); | |
uint32 flags = 0; | |
flags += b2DebugDraw::e_shapeBit; | |
flags += b2DebugDraw::e_jointBit; | |
flags += b2DebugDraw::e_aabbBit; | |
flags += b2DebugDraw::e_pairBit; | |
flags += b2DebugDraw::e_centerOfMassBit; | |
debugDraw->SetFlags(b2DebugDraw::e_shapeBit); | |
} | |
-(void)draw { | |
glDisable(GL_TEXTURE_2D);// | |
glDisableClientState(GL_COLOR_ARRAY);// | |
glDisableClientState(GL_TEXTURE_COORD_ARRAY);// | |
glEnableClientState(GL_VERTEX_ARRAY); | |
glPushMatrix(); | |
glScalef(PTM_RATIO, PTM_RATIO, 0); | |
world->DrawDebugData();// | |
glPopMatrix(); | |
//glDisableClientState(GL_VERTEX_ARRAY); <-------- You need GL_VERTEX_ARRAY enabled | |
glEnableClientState(GL_TEXTURE_COORD_ARRAY);// | |
glEnableClientState(GL_COLOR_ARRAY);// | |
glEnable(GL_TEXTURE_2D);// | |
} | |
**/ | |
/** | |
-(void) draw { //SCENE4 DRAW METHOD | |
glDisable(GL_TEXTURE_2D); | |
//glDisableClientState(GL_COLOR_ARRAY); | |
//glDisableClientState(GL_TEXTURE_COORD_ARRAY); | |
if (world) { | |
world->DrawDebugData(); | |
} | |
glEnable(GL_TEXTURE_2D); | |
//glEnableClientState(GL_COLOR_ARRAY); | |
//glEnableClientState(GL_TEXTURE_COORD_ARRAY); | |
[super draw]; | |
} | |
**/ | |
-(void) draw | |
{ | |
[super draw]; | |
ccGLEnableVertexAttribs( kCCVertexAttribFlag_Position ); | |
kmGLPushMatrix(); | |
world->DrawDebugData(); | |
kmGLPopMatrix(); | |
} | |
- (void)setupDebugDraw { //SCENE4 DRAW METHOD | |
//debugDraw = new GLESDebugDraw([[CCDirector sharedDirector] contentScaleFactor]);//PTM_RATIO* | |
debugDraw = new GLESDebugDraw(PTM_RATIO); | |
world->SetDebugDraw(debugDraw); | |
uint32 flags = 0; | |
flags += b2DebugDraw::e_shapeBit; | |
flags += b2DebugDraw::e_jointBit; | |
flags += b2DebugDraw::e_centerOfMassBit; | |
flags += b2DebugDraw::e_aabbBit; | |
flags += b2DebugDraw::e_pairBit; | |
debugDraw->SetFlags(flags); | |
//debugDraw->SetFlags(b2DebugDraw::e_shapeBit); | |
} | |
-(void)createGround { | |
CGSize winSize = [[CCDirector sharedDirector] winSize]; | |
float32 margin = 10.0f; | |
b2Vec2 lowerLeft = b2Vec2(margin/PTM_RATIO, margin/PTM_RATIO); | |
b2Vec2 lowerRight = b2Vec2((winSize.width*11-margin)/PTM_RATIO,margin/PTM_RATIO); | |
b2Vec2 upperRight = b2Vec2((winSize.width*11-margin)/PTM_RATIO,(winSize.height-margin)/PTM_RATIO); | |
b2Vec2 upperLeft = b2Vec2(margin/PTM_RATIO,(winSize.height-margin)/PTM_RATIO); | |
b2BodyDef groundBodyDef; | |
groundBodyDef.type = b2_staticBody; | |
groundBodyDef.position.Set(0, 0); | |
groundBody = world->CreateBody(&groundBodyDef); | |
b2PolygonShape groundShape; | |
b2FixtureDef groundFixtureDef; | |
groundFixtureDef.shape = &groundShape; | |
groundFixtureDef.density = 0.0; | |
groundShape.SetAsEdge(lowerLeft, lowerRight); | |
groundBody->CreateFixture(&groundFixtureDef); | |
groundShape.SetAsEdge(lowerRight, upperRight); | |
groundBody->CreateFixture(&groundFixtureDef); | |
groundShape.SetAsEdge(upperRight, upperLeft); | |
groundBody->CreateFixture(&groundFixtureDef); | |
groundShape.SetAsEdge(upperLeft, lowerLeft); | |
groundBody->CreateFixture(&groundFixtureDef); | |
} | |
-(void)createDividingBar{ | |
CGSize winSize = [[CCDirector sharedDirector] winSize]; | |
float32 margin = 10.0f; | |
b2Vec2 lowerLeft = b2Vec2((winSize.width*.40)/PTM_RATIO,(margin)/PTM_RATIO); | |
b2Vec2 lowerRight = b2Vec2((winSize.width*.60)/PTM_RATIO,(margin)/PTM_RATIO); | |
b2Vec2 upperRight = b2Vec2((winSize.width*.60)/PTM_RATIO,(winSize.height/4)/PTM_RATIO); | |
b2Vec2 upperLeft = b2Vec2((winSize.width*.40)/PTM_RATIO, (winSize.height/4)/PTM_RATIO); | |
b2BodyDef sideBodyDef; | |
sideBodyDef.type = b2_staticBody; | |
sideBodyDef.position.Set(0, 0); | |
sideBody = world->CreateBody(&sideBodyDef); | |
b2PolygonShape sideShape; | |
b2FixtureDef sideFixtureDef; | |
sideFixtureDef.shape = &sideShape; | |
sideFixtureDef.density = 0.0; | |
sideShape.SetAsEdge(lowerLeft, lowerRight); | |
sideBody->CreateFixture(&sideFixtureDef); | |
sideShape.SetAsEdge(lowerRight, upperRight); | |
sideBody->CreateFixture(&sideFixtureDef); | |
sideShape.SetAsEdge(upperRight, upperLeft); | |
sideBody->CreateFixture(&sideFixtureDef); | |
sideShape.SetAsEdge(upperLeft, lowerLeft); | |
sideBody->CreateFixture(&sideFixtureDef); | |
} | |
-(void)createDividingBar2{ | |
CGSize winSize = [[CCDirector sharedDirector] winSize]; | |
float32 margin = 10.0f; | |
b2Vec2 lowerLeft = b2Vec2(((winSize.width*3)*.90)/PTM_RATIO,(margin)/PTM_RATIO); | |
b2Vec2 lowerRight = b2Vec2(((winSize.width*3)*.95)/PTM_RATIO,(margin)/PTM_RATIO); | |
b2Vec2 upperRight = b2Vec2(((winSize.width*3)*.95)/PTM_RATIO,(winSize.height/4)/PTM_RATIO); | |
b2Vec2 upperLeft = b2Vec2(((winSize.width*3)*.90)/PTM_RATIO, (winSize.height/4)/PTM_RATIO); | |
b2BodyDef sideBodyDef; | |
sideBodyDef.type = b2_staticBody; | |
sideBodyDef.position.Set(0, 0); | |
sideBody = world->CreateBody(&sideBodyDef); | |
b2PolygonShape sideShape; | |
b2FixtureDef sideFixtureDef; | |
sideFixtureDef.shape = &sideShape; | |
sideFixtureDef.density = 0.0; | |
sideShape.SetAsEdge(lowerLeft, lowerRight); | |
sideBody->CreateFixture(&sideFixtureDef); | |
sideShape.SetAsEdge(lowerRight, upperRight); | |
sideBody->CreateFixture(&sideFixtureDef); | |
sideShape.SetAsEdge(upperRight, upperLeft); | |
sideBody->CreateFixture(&sideFixtureDef); | |
sideShape.SetAsEdge(upperLeft, lowerLeft); | |
sideBody->CreateFixture(&sideFixtureDef); | |
} | |
-(void)createSensor { | |
CGSize winSize = [[CCDirector sharedDirector] winSize]; | |
CGSize sensorSize = CGSizeMake(100, 50); | |
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) { | |
sensorSize = CGSizeMake(50, 25); | |
} | |
b2BodyDef bodyDef; | |
bodyDef.type = b2_staticBody; | |
bodyDef.position = b2Vec2((winSize.width)/PTM_RATIO, (sensorSize.height/2)/PTM_RATIO); | |
sensorBody = world->CreateBody(&bodyDef); | |
b2PolygonShape shape; | |
shape.SetAsBox(sensorSize.width/PTM_RATIO,sensorSize.height/PTM_RATIO); | |
b2FixtureDef fixtureDef; | |
fixtureDef.shape = &shape; | |
fixtureDef.isSensor = true; | |
sensorBody->CreateFixture(&fixtureDef); | |
} | |
-(void)instructions { | |
CGSize winSize = [[CCDirector sharedDirector] winSize]; | |
CCLabelTTF *label = [CCLabelTTF labelWithString:@"TURN OFF GRAVITY!" fontName:@"Helvetica" fontSize:48.0]; | |
label.position = ccp(winSize.width/2, winSize.height/2); | |
label.scale = 0.25; | |
[self addChild:label]; | |
CCScaleTo *scaleUp = [CCScaleTo actionWithDuration:1.0 scale:1.2]; | |
CCScaleTo *scaleBack = [CCScaleTo actionWithDuration:1.0 scale:1.0]; | |
CCDelayTime *delay = [CCDelayTime actionWithDuration:5.0]; | |
CCFadeOut *fade = [CCFadeOut actionWithDuration:2.0]; | |
CCSequence *sequence = [CCSequence actions:scaleUp, scaleBack, delay,fade, nil]; | |
[label runAction:sequence]; | |
} | |
-(void)winComplete:(id)sender { | |
[[GameManager sharedGameManager] setHasPlayerDied:NO]; | |
[[GameManager sharedGameManager] runSceneWithID:kLevelCompleteScene]; | |
} | |
-(void)win { | |
CGSize winSize = [[CCDirector sharedDirector] winSize]; | |
CCLabelTTF *label = [CCLabelTTF labelWithString:@"You Win!" fontName:@"Helvetica" fontSize:48.0]; | |
label.position = ccp(winSize.width/2, winSize.height/2); | |
label.scale = 0.25; | |
[self addChild:label]; | |
CCScaleTo *scaleUp = [CCScaleTo actionWithDuration:1.0 scale:1.2]; | |
CCScaleTo *scaleBack = [CCScaleTo actionWithDuration:1.0 scale:1.0]; | |
CCDelayTime *delay = [CCDelayTime actionWithDuration:2.0]; | |
CCCallFuncN *winComplete = [CCCallFuncN actionWithTarget:self selector:@selector(winComplete:)]; | |
CCSequence *sequence = [CCSequence actions:scaleUp, scaleBack, delay, winComplete, nil]; | |
[label runAction:sequence]; | |
} | |
// | |
-(void)followCart { | |
//if (actionStopped) return; | |
SantiBoy *santiboy = (SantiBoy*)[sceneSpriteBatchNode getChildByTag:kVikingSpriteTagValue]; | |
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { | |
groundMaxX = 11264; | |
} else { | |
groundMaxX = 5280; | |
} | |
CGSize winSize = [CCDirector sharedDirector].winSize; | |
float fixedPosition = winSize.width/4; | |
float newX = fixedPosition - santiboy.position.x; | |
newX = MIN(newX, fixedPosition); | |
newX = MAX(newX, -groundMaxX-fixedPosition); | |
CGPoint newPos = ccp(newX, self.position.y); | |
[self setPosition:newPos]; | |
} | |
-(id)init { | |
if ((self = [super init])) { | |
//mess with gravity | |
gravedad = 0.0f; | |
//[self addChild:[BoxDebugLayer debugLayerWithWorld:world ptmRatio:PTM_RATIO] z:10000]; | |
NSLog(@"PUZZLE LAYER ADDED TO SCENE"); | |
[self setupWorld]; | |
[self setupDebugDraw]; | |
[self scheduleUpdate]; | |
self.isTouchEnabled = YES; | |
//sensors | |
[self createSensor]; | |
[self instructions]; | |
} | |
self.isAccelerometerEnabled = TRUE; | |
[self createGround]; | |
[self createDividingBar]; | |
[self createDividingBar2]; | |
//create 3 boxes to test density, friction & restitution | |
CGPoint location1, location2, location3; | |
CGSize smallSize, medSize, largeSize; | |
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { | |
location1 = ccp(200, 400); | |
location2 = ccp(500, 400); | |
location3 = ccp(800, 400); | |
smallSize = CGSizeMake(50, 50); | |
medSize = CGSizeMake(100, 100); | |
largeSize = CGSizeMake(200, 200); | |
} else { | |
location1 = ccp(100, 200); | |
location2 = ccp(250, 200); | |
location3 = ccp(400, 200); | |
smallSize = CGSizeMake(25, 25); | |
medSize = CGSizeMake(50, 50); | |
largeSize = CGSizeMake(100, 100); | |
} | |
[self createBoxAtLocation:location1 withSize:smallSize friction:0.2 restitution:0.0 density:1.0]; | |
//[self createBoxAtLocation:location2 withSize:medSize friction:0.2 restitution:0.0 density:1.0]; | |
//[self createBoxAtLocation:location3 withSize:largeSize friction:0.2 restitution:0.0 density:1.0]; | |
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { | |
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"escapesceneatlas-iPad.plist"]; | |
sceneSpriteBatchNode = [CCSpriteBatchNode batchNodeWithFile:@"escapesceneatlas-iPad.png"]; | |
} else { | |
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"escapesceneatlas.plist"]; | |
sceneSpriteBatchNode = [CCSpriteBatchNode batchNodeWithFile:@"escapesceneatlas.png"]; | |
} | |
[self addChild:sceneSpriteBatchNode z:2]; | |
//CREATE MAIN CHARACTER | |
[self createSantiBoyAtLocation:ccp(40, 200)]; | |
//SCROLLING BACKGROUND CALLS | |
//[self addScrollingBackground]; | |
//[self addScrollingBackgroundWithParallax]; | |
//[self addScrollingBackgroundWithTileMapInsideParallax]; | |
[self newBackground]; | |
//ADD PARTICLE SYSTEM | |
// Add Snow Particle System | |
CCParticleSystem *snowParticleSystem = [CCParticleSnow node]; | |
[self addChild:snowParticleSystem]; | |
//Add EarthView & iPhone | |
CCSprite *earthView = [CCSprite spriteWithFile:@"earth.png"]; | |
CCSprite *iPhone = [CCSprite spriteWithFile:@"iphone.png"]; | |
[self addChild:earthView z:1]; | |
[self addChild:iPhone z:1]; | |
earthView.position = ccp(200,100); | |
iPhone.position = ccp(600,100); | |
//Load Atlas and then images of female | |
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { | |
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"Cosmonaut-iPad.plist"]; | |
femaleSpriteBatchNode = [CCSpriteBatchNode batchNodeWithFile:@"Cosmonaut-iPad.png"]; | |
} else { | |
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"Cosmonaut.plist"]; | |
femaleSpriteBatchNode = [CCSpriteBatchNode batchNodeWithFile:@"Cosmonaut.png"]; | |
} | |
[self addChild:femaleSpriteBatchNode z:1]; | |
//Load Atlas and then images of female2 | |
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { | |
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"Cosmonaut2.plist"]; | |
female2SpriteBatchNode = [CCSpriteBatchNode batchNodeWithFile:@"Cosmonaut2.png"]; | |
} else { | |
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"Cosmonaut2.plist"]; | |
female2SpriteBatchNode = [CCSpriteBatchNode batchNodeWithFile:@"Cosmonaut2.png"]; | |
} | |
[self addChild:female2SpriteBatchNode z:1]; | |
//Load Atlas and then images of female3 | |
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { | |
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"Cosmonaut3.plist"]; | |
female3SpriteBatchNode = [CCSpriteBatchNode batchNodeWithFile:@"Cosmonaut3.png"]; | |
} else { | |
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"Cosmonaut3.plist"]; | |
female3SpriteBatchNode = [CCSpriteBatchNode batchNodeWithFile:@"Cosmonaut3.png"]; | |
} | |
[self addChild:female3SpriteBatchNode z:1]; | |
//NSLog(@"female called"); //LARGE FOR IPAD | |
//female = [[Female alloc] initWithSpriteFrame:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:@"response_animation_frame0001.png"]]; | |
//female.position = ccp(200,120); | |
//[femaleSpriteBatchNode addChild:female z:1]; | |
//[female changeState:kStateSpawning]; | |
//[female release]; | |
//NSLog(@"female2 called"); //SMALL COLORED | |
female2 = [[Female2 alloc] initWithSpriteFrame:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:@"response2_animation_frame0001.png"]]; | |
CGSize winSize = [[CCDirector sharedDirector] winSize]; | |
float endX = (winSize.width*11-10)*0.9; | |
female2.position = ccp(endX,120); | |
[female2SpriteBatchNode addChild:female2 z:1]; | |
[female2 release]; | |
//NSLog(@"female3 called"); //SMALL BW | |
female3 = [[Female3 alloc] initWithSpriteFrame:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:@"response3_animation_frame0001.png"]]; | |
female3.position = ccp(300,120); | |
[female3SpriteBatchNode addChild:female3 z:1]; | |
[female3 release]; | |
return self; | |
} | |
-(void)newBackground{ | |
CGSize winSize = [CCDirector sharedDirector].winSize; | |
//Center of background image vars | |
float horiz = winSize.width/2; | |
float verti = winSize.height/2; | |
float offseteado = 0; | |
//if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { | |
//Add images to batchNode | |
for (int imageNumber=1; imageNumber < 11; imageNumber++) { | |
CCLOG(@"Adding image iss%d-iPhone-hd.png to the introAnimation.",imageNumber); | |
NSString *imageName = [NSString stringWithFormat:@"iss_inside_part%d.png", imageNumber]; | |
CCSprite *background = [CCSprite spriteWithFile:imageName]; | |
background.position = ccp(offseteado+((winSize.width/2)*imageNumber), verti); | |
offseteado = offseteado + winSize.width/2; | |
//background.position = ccp(winSize.width/2*imageNumber, winSize.height/2); | |
[self addChild:background z:0]; | |
} | |
/*} else { | |
//Add images to batchNode | |
for (int imageNumber=1; imageNumber < 7; imageNumber++) { | |
CCLOG(@"Adding image iss%d-iPhone.png to the introAnimation.",imageNumber); | |
NSString *imageName = [NSString stringWithFormat:@"iss%d-iPhone.png", imageNumber]; | |
CCSprite *background = [CCSprite spriteWithFile:imageName]; | |
background.position = ccp(horiz+(480*imageNumber), verti); | |
[self addChild:background z:0]; | |
//CCSprite *background = [CCSprite spriteWithSpriteFrameName:[NSString stringWithFormat:@"hn%d.jpg",imageNumber]]; | |
//background.position = ccp((winSize.width/2)*imageNumber, winSize.height/2); | |
//[_batchNode addChild:background z:1]; | |
}*/ | |
//} | |
} | |
#pragma mark SCROLLING_CALCULATION | |
/** | |
-(void)adjustLayer { | |
SantiBoy *santiboy = (SantiBoy*)[sceneSpriteBatchNode | |
getChildByTag:kVikingSpriteTagValue]; | |
float vikingXPosition = santiboy.position.x; | |
CGSize screenSize = [[CCDirector sharedDirector] winSize]; | |
float halfOfTheScreen = screenSize.width/2.0f; | |
CGSize levelSize = [[GameManager sharedGameManager] getDimensionsOfCurrentScene];// 6 | |
if ((vikingXPosition > halfOfTheScreen) && | |
(vikingXPosition < (levelSize.width - halfOfTheScreen))) { | |
// Background should scroll | |
float newXPosition = halfOfTheScreen - vikingXPosition; // 7 | |
[self setPosition:ccp(newXPosition,self.position.y)]; // 8 | |
} | |
} | |
**/ | |
-(void)accelerometer:(UIAccelerometer *)accelerometer | |
didAccelerate:(UIAcceleration *)acceleration { | |
b2Vec2 gravity(-acceleration.y * 15, acceleration.x *15); | |
world->SetGravity(gravity); | |
//SpaceGame code which makes the ship move... | |
/** | |
#define kFilteringFactor 0.1 | |
#define kRestAccelX -0.6 | |
#define kShipMaxPointsPerSec (winSize.height*0.5) | |
#define kMaxDiffX 0.2 | |
UIAccelerationValue rollingX, rollingY, rollingZ; | |
rollingX = (acceleration.x * kFilteringFactor) + (rollingX * (1.0 - kFilteringFactor)); | |
rollingY = (acceleration.y * kFilteringFactor) + (rollingY * (1.0 - kFilteringFactor)); | |
rollingZ = (acceleration.z * kFilteringFactor) + (rollingZ * (1.0 - kFilteringFactor)); | |
float accelX = acceleration.x - rollingX; | |
// float accelY = acceleration.y - rollingY; | |
// float accelZ = acceleration.z - rollingZ; | |
CGSize winSize = [CCDirector sharedDirector].winSize; | |
float accelDiff = accelX - kRestAccelX; | |
float accelFraction = accelDiff / kMaxDiffX; | |
float pointsPerSec = kShipMaxPointsPerSec * accelFraction; | |
_playerPointsPerSecY = pointsPerSec; | |
**/ | |
} | |
-(void)registerWithTouchDispatcher { | |
[[[CCDirector sharedDirector] touchDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES]; | |
//[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES]; | |
} | |
-(void)update:(ccTime)dt { | |
int32 velocityIterations = 3; | |
int32 positionIterations = 2; | |
world->Step(dt, velocityIterations, positionIterations); | |
//ASSOCIATE SPRITES WITH BODY | |
for(b2Body *b = world->GetBodyList(); b != NULL; b = b->GetNext()) { | |
if (b->GetUserData() != NULL) { | |
Box2DSprite *sprite = (Box2DSprite*) b->GetUserData(); | |
sprite.position = ccp(b->GetPosition().x * PTM_RATIO, | |
b->GetPosition().y * PTM_RATIO); | |
sprite.rotation = CC_RADIANS_TO_DEGREES(b->GetAngle() * -1); | |
} | |
} | |
//Update sprites | |
CCArray *listOfGameObjects = [sceneSpriteBatchNode children]; | |
for (GameCharacter *tempChar in listOfGameObjects) { | |
[tempChar updateStateWithDeltaTime:dt | |
andListOfGameObjects:listOfGameObjects]; | |
} | |
/** | |
// 3.b set new player position affected by accelerometer data | |
CGSize winSize = [CCDirector sharedDirector].winSize; | |
float maxY = winSize.height - santi.contentSize.height/2; | |
float minY = santi.contentSize.height/2; | |
float newY = santi.position.y + (_playerPointsPerSecY * dt); | |
newY = MIN(MAX(newY, minY), maxY); | |
santi.position = ccp(santi.position.x, newY); | |
**/ | |
////////SMALL TEST | |
if (CGRectIntersectsRect([santi boundingBox], [female2 boundingBox])) { | |
[female2 changeState:kStateSpawning]; | |
} | |
/////////SMALL TEST | |
if (CGRectIntersectsRect([santi boundingBox], [female3 boundingBox])) { | |
[female3 changeState:kStateSpawning]; | |
} | |
//Add code to test if player reached a certain point of maxScreenX to test for powerups & end game | |
//check for win/lose | |
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { | |
// IF IPAD CHECK POSITION | |
//NSLog(@"Players iPad Position %f", santi.position.x); | |
if (santi.position.x > 9600 && !hasWon) { | |
hasWon = YES; | |
NSLog(@"Santi passed 3600"); | |
[[GameManager sharedGameManager] setHasPlayerDied:NO]; | |
[[GameManager sharedGameManager] runSceneWithID:kLevelCompleteScene]; | |
} | |
} else { | |
// IF IPHONE CHECK POSITION | |
//NSLog(@"Players iPhone Position %f", santi.position.x); | |
if (santi.position.x > 5000 && !hasWon){ | |
hasWon = YES; | |
NSLog(@"Santi passed 600"); | |
[[GameManager sharedGameManager] setHasPlayerDied:NO]; | |
[[GameManager sharedGameManager] runSceneWithID:kLevelCompleteScene]; | |
} | |
} | |
/** | |
//adding SPRITES | |
for(b2Body *b = world->GetBodyList(); b != NULL; b = b->GetNext()) { | |
if (b->GetUserData() != NULL) { | |
Box2DSprite *sprite = (Box2DSprite*) b->GetUserData(); | |
sprite.position = ccp(b->GetPosition().x * PTM_RATIO, | |
b->GetPosition().y * PTM_RATIO); | |
sprite.rotation = CC_RADIANS_TO_DEGREES(b->GetAngle() * -1); | |
} | |
} | |
// sensors | |
if (!hasWon) { | |
b2ContactEdge* edge = frozenVikingBody->GetContactList(); | |
while (edge) | |
{ | |
b2Contact* contact = edge->contact; | |
b2Fixture* fixtureA = contact->GetFixtureA(); | |
b2Fixture* fixtureB = contact->GetFixtureB(); | |
b2Body *bodyA = fixtureA->GetBody(); | |
b2Body *bodyB = fixtureB->GetBody(); | |
if (bodyA == sensorBody || bodyB == sensorBody) { | |
hasWon = true; | |
[self win]; | |
break; | |
} | |
edge = edge->next; | |
} | |
} | |
**/ | |
[self followCart]; | |
//RESTRICT SPEED OF SANTI | |
if (santi.tag == kVikingSpriteTagValue) { | |
static int maxSpeed = 5; | |
b2Vec2 velocity = santiB2Body->GetLinearVelocity(); | |
float32 speed = velocity.Length(); | |
if (speed > maxSpeed) { | |
santiB2Body->SetLinearDamping(0.5); | |
} else if (speed < maxSpeed) { | |
santiB2Body->SetLinearDamping(0.0); | |
} | |
} | |
} | |
-(BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event { | |
//Get tap location and convert to cocos2d-box2d coordinates | |
CGPoint touchLocation = [touch locationInView:[touch view]]; | |
touchLocation = [[CCDirector sharedDirector] convertToGL:touchLocation]; | |
touchLocation = [self convertToNodeSpace:touchLocation]; | |
b2Vec2 locationWorld = b2Vec2(touchLocation.x/PTM_RATIO, touchLocation.y/PTM_RATIO); | |
//allows for user-touch draggable objects | |
b2AABB aabb; | |
b2Vec2 delta = b2Vec2(1.0/PTM_RATIO, 1.0/PTM_RATIO); | |
aabb.lowerBound = locationWorld - delta; | |
aabb.upperBound = locationWorld + delta; | |
SimpleQueryCallback callback(locationWorld); | |
world->QueryAABB(&callback, aabb); | |
//now that intersection is found, drag or create box | |
if (callback.fixtureFound) { | |
b2Body *body = callback.fixtureFound->GetBody(); | |
//added when adding extra objects | |
//Box2DSprite *sprite = (Box2DSprite *) body->GetUserData(); | |
//if (sprite == NULL) return FALSE; | |
//if(![sprite mouseJointBegan]) return FALSE; | |
b2MouseJointDef mouseJointDef; | |
mouseJointDef.bodyA = groundBody; | |
mouseJointDef.bodyB = body; | |
mouseJointDef.target = locationWorld; | |
mouseJointDef.maxForce = 100 * body->GetMass(); | |
mouseJointDef.collideConnected = true; | |
mouseJoint = (b2MouseJoint *) world->CreateJoint(&mouseJointDef); | |
body->SetAwake(true); | |
return YES; | |
} else { | |
// self create box at location | |
// OLD CODE[self createBoxAtLocation:touchLocation withSize:CGSizeMake(50, 50)]; | |
[self createBoxAtLocation:touchLocation withSize:CGSizeMake(50,50) friction:2 restitution:1 density:5]; | |
} | |
//mess with gravity - no, must make it a force | |
world->SetGravity(b2Vec2(0.0f,-10.0f)); | |
NSLog(@"touch started"); | |
return TRUE; | |
} | |
-(void) ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event { | |
CGPoint touchLocation = [touch locationInView:[touch view]]; | |
touchLocation = [[CCDirector sharedDirector] convertToGL:touchLocation]; | |
touchLocation = [self convertToNodeSpace:touchLocation]; | |
b2Vec2 locationWorld = b2Vec2(touchLocation.x/PTM_RATIO, touchLocation.y/PTM_RATIO); | |
if (mouseJoint) { | |
mouseJoint->SetTarget(locationWorld); | |
} | |
} | |
-(void) ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event { | |
if (mouseJoint) { | |
world->DestroyJoint(mouseJoint); | |
mouseJoint = NULL; | |
} | |
} | |
@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
#import "SantiBoy.h" | |
@implementation SantiBoy | |
@synthesize isOnGround; | |
//call animations | |
-(void)initAnimations { | |
walkingAnim = [self loadPlistForAnimationWithName:@"walkingAnim" andClassName:NSStringFromClass([self class])]; | |
walkingAnim.restoreOriginalFrame = YES; | |
[[CCAnimationCache sharedAnimationCache] addAnimation:walkingAnim name:@"walkingAnim"]; | |
jumpingAnim = [self loadPlistForAnimationWithName:@"jumpingAnim" andClassName:NSStringFromClass([self class])]; | |
walkingAnim.restoreOriginalFrame = NO; | |
[[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:@"hopper_run_animation_frame1.png"]]; | |
break; | |
case kStateWalking: | |
action = [CCAnimate actionWithAnimation:walkingAnim]; | |
NSLog(@"kStateWalking"); | |
break; | |
case kStateJumping: | |
action = [CCAnimate actionWithAnimation:jumpingAnim]; | |
break; | |
case kStateTakingDamage: | |
//[self playHitEffect]; | |
//characterHealth = characterHealth - 10; | |
action = [CCBlink actionWithDuration:1.0 blinks:6.0]; | |
break; | |
default: | |
break; | |
} | |
if (action != nil) { | |
[self runAction:action]; | |
} | |
} | |
-(id) init { | |
if((self = [super init])) { | |
[self setDisplayFrame:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:@"hopper_run_animation_frame1.png"]]; | |
gameObjectType = kFrozenVikingType; | |
[self initAnimations]; | |
} | |
return self; | |
} | |
- (void) updateStateWithDeltaTime:(ccTime)deltaTime | |
andListOfGameObjects:(CCArray *)listOfGameObjects { | |
//1. ANIMATE IF SANTIBOY IS MOVING FAST | |
b2Vec2 currentVel = self.body->GetLinearVelocity(); | |
if ( currentVel.y > 5) { | |
[self changeState:kStateWalking]; | |
} /*else if (currentVel.y < 5) { | |
[self changeState:kStateIdle]; | |
}*/ | |
//2. PREVENT HIM FROM SPINNING AROUND -- DO WE WANT THIS OR LET HIM SPIN AND ADD ANIMATION??? | |
float32 minAngle = CC_DEGREES_TO_RADIANS(-10); | |
float32 maxAngle = CC_DEGREES_TO_RADIANS(10); | |
double desiredAngle = self.body->GetAngle(); | |
if (self.body->GetAngle() > maxAngle) { | |
desiredAngle = maxAngle; | |
} else if (self.body->GetAngle() < minAngle) { | |
desiredAngle = minAngle; | |
} | |
float32 diff = desiredAngle - self.body->GetAngle(); | |
if (diff != 0) { | |
body->SetAngularVelocity(0); | |
float32 diff = desiredAngle - self.body->GetAngle(); | |
float angimp = self.body->GetInertia() * diff; | |
self.body->ApplyAngularImpulse(angimp * 2); | |
} | |
//3. SET A JUMP FACTOR | |
float jumpFactor; | |
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { | |
jumpFactor = 300.0; | |
} else { | |
jumpFactor = 250.0; | |
} | |
//4. USE JUMP FACTOR | |
double timeJumping = CACurrentMediaTime()-jumpStartTime; | |
if (jumpStartTime != 0 && timeJumping < 0.25) { | |
currentVel.y = jumpFactor*2; | |
self.body->ApplyLinearImpulse( b2Vec2(0,50), self.body->GetWorldCenter() ); | |
//self.body->SetLinearVelocity(currentVel); | |
} | |
// SET VELOCITY AFFECTED BY ACCEL | |
if (ABS(accelerationFraction) < 0.05) { | |
accelerationFraction = 0; | |
currentVel.x = 0; | |
self.body->SetLinearVelocity(currentVel); | |
} else { | |
float maxSpeed = 200.0f; | |
currentVel.x = (-maxSpeed*accelerationFraction); | |
self.body->SetLinearVelocity(currentVel); | |
self.body->SetAwake(true); | |
} | |
//b2Vec2 newVel = self.body->GetLinearVelocity(); | |
//newVel = ccp(jumpFactor*accelerationFraction,self.body->GetLinearVelocity()); | |
//self.body->SetLinearVelocity(newVel); | |
/* | |
// - ///////////////////////////////////////////////////////////////////////////////////////// | |
// - IF IN THE AIR DONT LET HIM JUMP | |
// - IF ON GROUND LET HIM JUMP | |
if (self.isOnGround == FALSE) { | |
} | |
//NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults]; | |
//float calibrationFloat = [prefs floatForKey:@"X-Calibrate"]; | |
//float calibratedFloat = (acceleration.x - calibrationFloat); | |
// AROUND SET VELOCITY AFFECTED BY ACCEL | |
if (self.isOnGround == TRUE) { | |
} else { | |
self.body->SetLinearVelocity(ccp(0, 0)); | |
} | |
// AROUND SET VELOCITY AFFECTED BY ACCEL | |
// MAY NOT NEED THIS BECAUSE OF GROUNDS BOUNDS-prevent sprite from flying off the sides when in the air | |
float margin = 70; | |
CGSize winSize = [CCDirector sharedDirector].winSize; | |
if (self.position.x < margin) { | |
cpBodySetPos(body, ccp(margin, self.position.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; | |
} | |
} | |
} | |
// MAY NOT NEED THIS BECAUSE OF GROUNDS BOUNDS | |
*/ | |
if (characterState == kStateIdle && accelerationFraction != 0) { | |
[self changeState:kStateWalking]; | |
} | |
if ([self numberOfRunningActions] == 0 && characterState != kStateIdle) { | |
[self changeState:kStateIdle]; | |
} | |
// - ///////////////////////////////////////////////////////////////////////////////////////// | |
} | |
////CONTROL HOW HOPPER JUMPS | |
- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event { | |
//self.body->SetTransform( b2Vec2(10,20), 0 ); | |
jumpStartTime = CACurrentMediaTime(); | |
return TRUE; | |
} | |
- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event { | |
jumpStartTime = 0; | |
} | |
//tiltAngle = ccpToAngle( ccp( acceleration.y, acceleration.z ) ) - ccpToAngle( calibrationVector ); | |
- (void)accelerometer:(UIAccelerometer*)accelerometer didAccelerate:(UIAcceleration*)acceleration { | |
UIInterfaceOrientation orientation = [[UIDevice currentDevice] orientation]; | |
//b2Vec2 calibrationVector = ccp( acceleration.y, acceleration.z ); | |
accelerationFraction = acceleration.y*2; | |
if (accelerationFraction < -1) { | |
accelerationFraction = -1; | |
} else if (accelerationFraction > 1) { | |
accelerationFraction = 1; | |
} | |
//API CHANGE set delegate to self | |
if (orientation == UIDeviceOrientationLandscapeLeft){ | |
accelerationFraction *= -1; | |
} | |
} | |
- (BOOL)mouseJointBegan { | |
return FALSE; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment