sdf

来源:互联网 发布:网络女主播这么赚钱 编辑:程序博客网 时间:2024/06/07 02:31

//

//  GameOverLoseScene.h

//  bcamcocos2dtutorial1

//

//  Created by bcam2 on 6/9/10.

//  Copyright 2010 Geek And Dad. All rights reserved.

//


#import <Foundation/Foundation.h>

#import "cocos2d.h"

 

@interface GameOverLayer : CCColorLayer {

  CCLabel *_label;

}

@property (nonatomic, retain) CCLabel *label;

@end

 

@interface GameOverScene : CCScene {

  GameOverLayer *_layer;

}

@property (nonatomic, retain) GameOverLayer *layer;

@end




//

//  GameOverLoseScene.m

//  bcamcocos2dtutorial1

//

//  Created by bcam2 on 6/9/10.

//  Copyright 2010 Geek And Dad. All rights reserved.

//


#import "GameOverScene.h"

#import "HelloWorldScene.h"

 

@implementation GameOverScene

@synthesize layer = _layer;

 

- (id)init {

 

  if ((self = [superinit])) {

    self.layer = [GameOverLayernode];

    [self addChild:_layer];

  }

  return self;

}

 

- (void)dealloc {

  [_layerrelease];

  _layer = nil;

  [superdealloc];

}

 

@end

 

@implementation GameOverLayer

@synthesize label = _label;

 

-(id) init

{

  if( (self=[superinitWithColor:ccc4(255,255,255,255)] )) {

 

    CGSize winSize = [[CCDirectorsharedDirector] winSize];

    self.label = [CCLabellabelWithString:@""fontName:@"Arial"fontSize:32];

    _label.color = ccc3(0,0,0);

    _label.position =ccp(winSize.width/2, winSize.height/2);

    [self addChild:_label];

 

    [selfrunAction:[CCSequenceactions:

      [CCDelayTimeactionWithDuration:3],

      [CCCallFunc actionWithTarget:selfselector:@selector(gameOverDone)],

      nil]];

 

  }

  return self;

}

 

- (void)gameOverDone {

 

  [[CCDirectorsharedDirector] replaceScene:[HelloWorldscene]];

 

}

 

- (void)dealloc {

  [_labelrelease];

  _label = nil;

  [superdealloc];

}

 

@end




// When you import this file, you import all the cocos2d classes

#import "cocos2d.h"


@class HelloWorld;

@interface HelloWorldHud : CCLayer

{   

    CCLabel *label;

HelloWorld *_gameLayer;

}


@property (nonatomic, retain) HelloWorld *gameLayer;


- (void)numCollectedChanged:(int)numCollected;

@end


// HelloWorld Layer

@interface HelloWorld : CCLayer

{

    CCTMXTiledMap *_tileMap; //地图

    CCTMXLayer *_background;   //地图的layer 上面放置背景  如墙 这些

    CCTMXLayer *_foreground; //前景层  放西瓜 可以拾取东西

    CCTMXLayer *_meta;//标记地图是否可以通过

    CCSprite *_player;//玩家

    int _numCollected;//收集西瓜数统计

    HelloWorldHud *_hud;  //相当于窗口句柄

int _mode;//模式 移动和开枪模式

    

NSMutableArray *_enemies;  //产生敌人数组

NSMutableArray *_projectiles;//子弹数组

}


@property (nonatomic, retain) CCTMXTiledMap *tileMap;

@property (nonatomic, retain) CCTMXLayer *background;

@property (nonatomic, retain) CCTMXLayer *foreground;

@property (nonatomic, retain) CCTMXLayer *meta;

@property (nonatomic, retain) CCSprite *player;

@property (nonatomic, assign) int numCollected;

@property (nonatomic, assign) int mode;

@property (nonatomic, retain) HelloWorldHud *hud;


// returns a Scene that contains the HelloWorld as the only child

+(id) scene;


@end

//

// cocos2d Hello World example

// http://www.cocos2d-iphone.org

//


// Import the interfaces

#import "HelloWorldScene.h"

#import "GameOverScene.h"

#import "SimpleAudioEngine.h"


@implementation HelloWorldHud

@synthesize gameLayer = _gameLayer;



-(id) init

{

    if ((self = [superinit])) {

        //获取窗口大小

        CGSize winSize = [[CCDirectorsharedDirector] winSize];

        //计分lable

        label = [CCLabellabelWithString:@"0"dimensions:CGSizeMake(50,20) alignment:UITextAlignmentRightfontName:@"Verdana-Bold"fontSize:18.0];

        label.color =ccc3(0,0,0);

        

        int margin = 10;

        label.position =ccp(winSize.width - (label.contentSize.width/2) - margin,label.contentSize.height/2 + margin);

        [self addChild:label];

        

CCMenuItem *on; 

CCMenuItem *off;

on = [[CCMenuItemImageitemFromNormalImage:@"projectile-button-on.png" 

  selectedImage:@"projectile-button-on.png"target:nilselector:nil]retain];

off = [[CCMenuItemImageitemFromNormalImage:@"projectile-button-off.png" 

  selectedImage:@"projectile-button-off.png"target:nilselector:nil]retain];

CCMenuItemToggle *toggleItem = [CCMenuItemToggleitemWithTarget:self 

  selector:@selector(projectileButtonTapped:)items:off, on, nil];

CCMenu *toggleMenu = [CCMenumenuWithItems:toggleItem, nil];

toggleMenu.position =ccp(100, 32);

[self addChild:toggleMenu];

    }

    return self;

}


//mode 0 = moving mode

//mode 1 = ninja star throwing mode

- (void)projectileButtonTapped:(id)sender

{

    if (_gameLayer.mode ==1){

_gameLayer.mode =0;

}else{

_gameLayer.mode =1;

}

}


- (void)numCollectedChanged:(int)numCollected {

    [label setString:[NSStringstringWithFormat:@"%d", numCollected]];

}


@end


// HelloWorld implementation

@implementation HelloWorld

@synthesize tileMap = _tileMap;

@synthesize background = _background;

@synthesize foreground = _foreground;

@synthesize meta = _meta;

@synthesize player = _player;

@synthesize numCollected = _numCollected;

@synthesize hud = _hud;

@synthesize mode = _mode;


+(id) scene

{

// 'scene' is an autorelease object.

CCScene *scene = [CCScenenode];

// 'layer' is an autorelease object.

HelloWorld *layer = [HelloWorldnode];

// add layer as a child to scene

[scene addChild: layer];

    

    HelloWorldHud *hud = [HelloWorldHudnode];    

    [scene addChild: hud];

    

    layer.hud = hud;

    hud.gameLayer = layer;

// return the scene

return scene;

}


-(void)setViewpointCenter:(CGPoint) position {

    

    CGSize winSize = [[CCDirectorsharedDirector] winSize];

    

    int x = MAX(position.x, winSize.width /2);

    int y = MAX(position.y, winSize.height /2);

    x = MIN(x, (_tileMap.mapSize.width *_tileMap.tileSize.width) - winSize.width /2);

    y = MIN(y, (_tileMap.mapSize.height *_tileMap.tileSize.height) - winSize.height/2);

    CGPoint actualPosition = ccp(x, y);

    

    CGPoint centerOfView = ccp(winSize.width/2, winSize.height/2);

    CGPoint viewPoint = ccpSub(centerOfView, actualPosition);

    self.position = viewPoint;

    

}


-(void) animateEnemy:(CCSprite*)enemy

{

  //speed of the enemy

  ccTime actualDuration = .1;

 

  // Create the actions

  id actionMove = [CCMoveByactionWithDuration:actualDuration 

    position:ccpMult(ccpNormalize(ccpSub(_player.position,enemy.position)),10)];

  id actionMoveDone = [CCCallFuncNactionWithTarget:self 

    selector:@selector(enemyMoveFinished:)];

  [enemy runAction:[CCSequenceactions:actionMove, actionMoveDone, nil]]; 

}


-(void)enemyMoveFinished:(id)sender {

CCSprite *enemy = (CCSprite *)sender;

CGPoint diff =ccpSub(_player.position,enemy.position);

float angleRadians = atanf((float)diff.y / (float)diff.x);

float angleDegrees = CC_RADIANS_TO_DEGREES(angleRadians);

float cocosAngle = -1 * angleDegrees;

if (diff.x <0){

cocosAngle += 180;

}

enemy.rotation = cocosAngle;

[self animateEnemy: enemy]; 

}


-(void)addEnemyAtX:(int)x y:(int)y {

  CCSprite *enemy = [CCSpritespriteWithFile:@"enemy1.png"]; 

  enemy.position = ccp(x, y);

  [self addChild:enemy];

  [_enemies addObject:enemy];

  [self animateEnemy: enemy]; 

NSLog(@"%@", enemy);

}


- (void)lose {

GameOverScene *gameOverScene = [GameOverScenenode];

[gameOverScene.layer.labelsetString:@"You Lose!"];

[[CCDirectorsharedDirector] replaceScene:gameOverScene];

}


- (void)win {

GameOverScene *gameOverScene = [GameOverScenenode];

[gameOverScene.layer.labelsetString:@"You Win!"];

[[CCDirectorsharedDirector] replaceScene:gameOverScene];

}


- (void)testCollisions:(ccTime)dt {

  for (CCSprite *targetin _enemies) {

    CGRect targetRect = CGRectMake(

  target.position.x - (target.contentSize.width/2), 

  target.position.y - (target.contentSize.height/2), 

  target.contentSize.width

  target.contentSize.height);

if (CGRectContainsPoint(targetRect,_player.position)) {

  [self lose];

}

  }

  

  NSMutableArray *projectilesToDelete = [[NSMutableArrayalloc] init];

  // iterate through projectiles

  for (CCSprite *projectilein _projectiles) {

NSLog(@"projectile: %d enemies", [_enemiescount]);

    CGRect projectileRect = CGRectMake(

      projectile.position.x - (projectile.contentSize.width/2), 

      projectile.position.y - (projectile.contentSize.height/2), 

      projectile.contentSize.width

      projectile.contentSize.height);

 

    NSMutableArray *targetsToDelete = [[NSMutableArrayalloc] init];

// iterate through enemies, see if any intersect with currnet projectile

    for (CCSprite *targetin _enemies) {

  NSLog(@"enemy");

      CGRect targetRect = CGRectMake(

        target.position.x - (target.contentSize.width/2), 

        target.position.y - (target.contentSize.height/2), 

        target.contentSize.width

        target.contentSize.height);

 

      if (CGRectIntersectsRect(projectileRect, targetRect)) {

        [targetsToDelete addObject:target];

NSLog(@"collision");

      }

    }

 

    // delete all hit enemies

for (CCSprite *targetin targetsToDelete) {

      [_enemies removeObject:target];

      [self removeChild:targetcleanup:YES];

    }

 

    if (targetsToDelete.count >0) {

      // add the projectile to the list of ones to remove

  [projectilesToDelete addObject:projectile];

    }

    [targetsToDelete release];

  }

  // remove all the projectiles that hit.

  for (CCSprite *projectilein projectilesToDelete) {

    [_projectiles removeObject:projectile];

    [self removeChild:projectilecleanup:YES];

  }

  [projectilesToDelete release];

}


// on "init" you need to initialize your instance

-(id) init

{

    if( (self=[superinit] )) {

        

        [[SimpleAudioEnginesharedEngine] preloadEffect:@"pickup.caf"];

        [[SimpleAudioEnginesharedEngine] preloadEffect:@"hit.caf"];

        [[SimpleAudioEnginesharedEngine] preloadEffect:@"move.caf"];

        [[SimpleAudioEnginesharedEngine] playBackgroundMusic:@"TileMap.caf"];

        

        self.isTouchEnabled =YES;

        

        self.tileMap = [CCTMXTiledMaptiledMapWithTMXFile:@"TileMap.tmx"];

        self.background = [_tileMaplayerNamed:@"Background"];

        self.foreground = [_tileMaplayerNamed:@"Foreground"];

        self.meta = [_tileMaplayerNamed:@"Meta"];

        _meta.visible =NO;

_mode = 0;


        // Find spawn point x,y coordinates

        CCTMXObjectGroup *objects = [_tileMapobjectGroupNamed:@"Objects"];

        NSMutableDictionary *spawnPoints = [objectsobjectNamed:@"SpawnPoint"];

        NSAssert(spawnPoints.count >0, @"SpawnPoint object missing");

        int x = [[spawnPoints valueForKey:@"x"] intValue];

        int y = [[spawnPoints valueForKey:@"y"] intValue];


        // Create a player sprite at the x,y coordinates

        self.player = [CCSpritespriteWithFile:@"Player.png"];

        _player.position =ccp(x, y);

        [self addChild:_player]; 

//after creating the player

//iterate through objects, finding all enemy spawn points and creating enemies.

NSMutableDictionary * spawnPoint;

_enemies = [[NSMutableArrayalloc] init];

_projectiles = [[NSMutableArrayalloc] init];

for (spawnPoint in [objects objects]) {

if ([[spawnPointvalueForKey:@"Enemy"] intValue] == 1){

x = [[spawnPointvalueForKey:@"x"] intValue];

y = [[spawnPointvalueForKey:@"y"] intValue];

[selfaddEnemyAtX:x y:y];

}

}


        // Center the view on the player (or as close as we can!)

        [selfsetViewpointCenter:_player.position];

                    

        [self addChild:_tileMapz:-1];

[self schedule:@selector(testCollisions:)];

    }

    return self;

}


- (CGPoint)tileCoordForPosition:(CGPoint)position {

    int x = position.x /_tileMap.tileSize.width;

    int y = ((_tileMap.mapSize.height *_tileMap.tileSize.height) - position.y) /_tileMap.tileSize.height;

    return ccp(x, y);

}


-(void) registerWithTouchDispatcher

{

[[CCTouchDispatchersharedDispatcher] addTargetedDelegate:selfpriority:0swallowsTouches:YES];

}


-(BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event

{

return YES;

}


-(void)setPlayerPosition:(CGPoint)position {


    CGPoint tileCoord = [selftileCoordForPosition:position];

    int tileGid = [_metatileGIDAt:tileCoord];

    if (tileGid) {

        NSDictionary *properties = [_tileMappropertiesForGID:tileGid];

        if (properties) {

            NSString *collision = [propertiesvalueForKey:@"Collidable"];

            if (collision && [collision compare:@"True"] == NSOrderedSame) {

                [[SimpleAudioEngine sharedEngine] playEffect:@"hit.caf"];

                return;

            }

            NSString *collectable = [propertiesvalueForKey:@"Collectable"];

            if (collectable && [collectablecompare:@"True"] == NSOrderedSame) {

                [_meta removeTileAt:tileCoord];

                [_foreground removeTileAt:tileCoord];

                self.numCollected++;

                [_hud numCollectedChanged:_numCollected];

                [[SimpleAudioEngine sharedEngine] playEffect:@"pickup.caf"];

if (_numCollected ==2){ // put the number of melons on your map in place of the '2'

[selfwin];

}

            }

        }

    }

    [[SimpleAudioEnginesharedEngine] playEffect:@"move.caf"];

    _player.position = position;


}


-(void)projectileMoveFinished:(id)sender {

  CCSprite *sprite = (CCSprite *)sender;

  [selfremoveChild:sprite cleanup:YES];

  [_projectiles removeObject:sprite];

}


-(void) ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event

{

if (_mode ==0)

{

CGPoint touchLocation = [touchlocationInView: [touch view]];

touchLocation = [[CCDirectorsharedDirector] convertToGL: touchLocation];

touchLocation = [selfconvertToNodeSpace:touchLocation];

CGPoint playerPos =_player.position;

CGPoint diff = ccpSub(touchLocation, playerPos);

if (abs(diff.x) >abs(diff.y)) {

if (diff.x >0) {

playerPos.x +=_tileMap.tileSize.width;

} else {

playerPos.x -=_tileMap.tileSize.width

}    

} else {

if (diff.y >0) {

playerPos.y +=_tileMap.tileSize.height;

} else {

playerPos.y -=_tileMap.tileSize.height;

}

}

//player.position = playerPos; // Todo: Trymove

[selfsetPlayerPosition:playerPos];

[selfsetViewpointCenter:_player.position];

} else {

// Find where the touch is

CGPoint touchLocation = [touchlocationInView: [touch view]];

touchLocation = [[CCDirectorsharedDirector] convertToGL: touchLocation];

touchLocation = [selfconvertToNodeSpace:touchLocation];


// Create a projectile and put it at the player's location

CCSprite *projectile = [CCSpritespriteWithFile:@"Projectile.png"];

projectile.position =_player.position;

[self addChild:projectile];


// Determine where we wish to shoot the projectile to

int realX;

// Are we shooting to the left or right?

CGPoint diff = ccpSub(touchLocation, _player.position);

if (diff.x >0)

{

realX = (_tileMap.mapSize.width *_tileMap.tileSize.width) + (projectile.contentSize.width/2);

}else{

realX = -(_tileMap.mapSize.width *_tileMap.tileSize.width) - (projectile.contentSize.width/2);

}

float ratio = (float) diff.y / (float) diff.x;

int realY = ((realX - projectile.position.x) * ratio) + projectile.position.y;

CGPoint realDest =ccp(realX, realY);

// Determine the length of how far we're shooting

int offRealX = realX - projectile.position.x;

int offRealY = realY - projectile.position.y;

float length = sqrtf((offRealX*offRealX)+(offRealY*offRealY));

float velocity = 480/1; // 480pixels/1sec

float realMoveDuration = length/velocity;


// Move projectile to actual endpoint

id actionMoveDone = [CCCallFuncNactionWithTarget:self 

selector:@selector(projectileMoveFinished:)];

[projectile runAction:[CCSequenceactionOne:[CCMoveTo actionWithDuration:realMoveDuration position:realDest]two: actionMoveDone]];

[_projectiles addObject:projectile];

}

    

}


// on "dealloc" you need to release all your retained objects

- (void) dealloc

{

// in case you have something to dealloc, do it in this method

// in this particular example nothing needs to be released.

// cocos2d will automatically release all the children (Label)

self.tileMap =nil;

    self.background =nil;

    self.foreground =nil;

    self.meta = nil;

    self.player = nil;

    self.hud = nil;

// don't forget to call "super dealloc"

[superdealloc];

}

@end


原创粉丝点击