gamelayer.h/gamelayer.m

//

//  GameLayer.h

//  EndlessPlatformer

//

//  Created by Kay Rules on 8/1/11.

//  Copyright 2011 Fleezo.com. All rights reserved.

//

 

#import <Foundation/Foundation.h>

#import "cocos2d.h"

#import "MovingPlatform.h"

#import "ScoreLayer.h"

 

 

@interface GameLayer : CCLayer {

    MovingPlatform *platform;

    ScoreLayer *scoreLayer;

    

    CCSpriteBatchNode *_batchNode;

    CCSprite *_hero;

    CCAction *_runAction;

    

    CGSize winSize;

    CGPoint heroRunningPosition;

CGPoint jumpVelocity;

    

    BOOL isJumping;

    BOOL isGap;

    

    int _score;

    int _nextEnemy;

}

 

@property (nonatomic, retain) CCSprite *hero;

@property (nonatomic, retain) CCAction *runAction;

@property CGPoint heroRunningPosition;

@property CGPoint jumpVelocity;

@propertyBOOL isJumping;

@propertyBOOL isGap;

@propertyint score;

 

+(CCScene *) scene;

 

 

@end

 

 

 

 

gamelayer.m

 

 

//

//  GameLayer.m

//  EndlessPlatformer

//

//  Created by Kay Rules on 8/1/11.

//  Copyright 2011 Fleezo.com. All rights reserved.

//

 

#import "GameLayer.h"

#import "GameOverScene.h"

 

 

#define kInitialSpeed 4

#define kTagStepDistance 0

#define kJumpHigh 19

#define kJumpShort 13

#define kGravityFactor -1

#define kPlatformHeadSize 40

#define kDifficultySpeed 0.8

#define kDifficultyScore 100

#define kInitialEnemies 10

 

 

@interface GameLayer (private)

- (void) initBackground;

- (void) initPlatform;

- (void) initEnemy;

- (void) gameOver;

- (void) createHero;

- (void) changeHeroImageDuringJump;

- (void) initScore;

- (void) updateScore;

- (void) increaseDifficulty;

@end

 

@implementation GameLayer

 

@synthesize hero = _hero;

@synthesize score = _score;

@synthesize runAction = _runAction;

@synthesize isJumping;

@synthesize isGap;

@synthesize jumpVelocity;

@synthesize heroRunningPosition;

 

 

+(CCScene *) scene

{

CCScene *scene = [CCScene node];

GameLayer *layer = [GameLayernode];

[scene addChild: layer];

    return scene;

}

 

-(id) init

{

if( (self=[super init])) {

        self.isTouchEnabled = YES;

isJumping = NO;

        isGap = NO;

        jumpVelocity = CGPointZero;

        

        winSize = [CCDirector sharedDirector].winSize;        

        heroRunningPosition = ccp(winSize.width * 0.25, winSize.height * 0.5 - kPlatformHeadSize + 6);

        

        [self initPlatform];

        [self createHero];

        [selfinitBackground];

        [self initScore];

}

returnself;

}

 

- (void) initPlatform

{

    CCArray *images = [[CCArray alloc] initWithCapacity:3];

    [images addObject:@"platform-left.png"];

    [images addObject:@"platform.png"];

    [images addObject:@"platform-right.png"];

    

    platform = [[MovingPlatformalloc] initWithSpeed:kInitialSpeedandPause:NOandImages:images];

    

    [self addChild:platform z:0];

    [selfscheduleUpdate];

}

 

 

- (void) initBackground 

{

    CCSprite *background = [CCSprite spriteWithFile:@"background.png"];

    background.anchorPoint = CGPointZero;

    background.position = CGPointZero;

    [self addChild:background z:-1];

}

 

 

-(void) createHero

{

    _batchNode = [CCSpriteBatchNodebatchNodeWithFile:@"Snipe.png"];

    [selfaddChild:_batchNode];

    [[CCSpriteFrameCachesharedSpriteFrameCache] addSpriteFramesWithFile:@"Snipe.plist"];

    

    //gather list of frames

    NSMutableArray *runAnimFrames = [NSMutableArrayarray];

    for(int i = 1; i <= 8; ++i) {

        [runAnimFrames addObject:

         [[CCSpriteFrameCachesharedSpriteFrameCache] spriteFrameByName:

          [NSString stringWithFormat:@"snipe-%d.png", i]]];

    }

    

    //create sprite and run the hero

    self.hero = [CCSpritespriteWithSpriteFrameName:@"snipe-8.png"];

    _hero.anchorPoint = CGPointZero;

    _hero.position = self.heroRunningPosition;

    

    //create the animation object

    CCAnimation *runAnim = [CCAnimation animationWithFrames:runAnimFrames delay:0.1f];

    self.runAction = [CCRepeatForeveractionWithAction: [CCAnimateactionWithAnimation:runAnim restoreOriginalFrame:YES]];

    

    [_herorunAction:_runAction];

    [_batchNodeaddChild:_heroz:0];

}

 

 

 

 

-(void) update:(ccTime)dt

{

    CGPoint returnedCoordinate = [platform getYCoordinateAt:heroRunningPosition];    

    if (heroRunningPosition.y != returnedCoordinate.y) {

        heroRunningPosition = ccp(heroRunningPosition.x, returnedCoordinate.y - kPlatformHeadSize);

    }

    

    //falling between gap

    if (returnedCoordinate.x <= 0 && returnedCoordinate.y <= 0) {

        isGap = YES;

        heroRunningPosition = ccp(heroRunningPosition.x, -_hero.textureRect.size.height);

        if (isJumping == NO) {

            jumpVelocity = ccpAdd(jumpVelocity, ccp(0,kGravityFactor));

            _hero.position = ccpAdd(_hero.position, jumpVelocity);

            if (_hero.position.y < heroRunningPosition.y) {

                [self gameOver];

            }

        }

    } else {

        isGap = NO;

    }

    

    if (_hero.position.y < heroRunningPosition.y) {

        if (jumpVelocity.y >= 0) {

            _hero.position = ccp(heroRunningPosition.x - _hero.textureRect.size.width*2

                                 heroRunningPosition.y);

        }

        jumpVelocity = ccpAdd(jumpVelocity, ccp(0,kGravityFactor));

        _hero.position = ccpAdd(_hero.position, jumpVelocity);

        [platform paused:YES];

        [_herostopAllActions];

        if (_hero.position.y < -winSize.height) {

            [self gameOver];

        }

    }

}

 

 

 

-(void)jump:(ccTime)delta 

{

if (isJumping == YES) {

        if (jumpVelocity.y < 0 && 

            _hero.position.y > heroRunningPosition.y &&

            _hero.position.y < heroRunningPosition.y + _hero.textureRect.size.height) {

            //hero landed

            _hero.position = heroRunningPosition;

            jumpVelocity = CGPointZero;

            

            [self unschedule:@selector(jump:)];

            isJumping = NO;

            //NSLog(@"run action.");

            if (_hero.position.y <= heroRunningPosition.y) [_herorunAction:_runAction];

            

        } else {

//make the hero jump with gravity=-1

            jumpVelocity = ccpAdd(jumpVelocity, ccp(0,kGravityFactor));

            _hero.position = ccpAdd(_hero.position, jumpVelocity);

            //change jumping image

            [_hero stopAllActions];

            [selfchangeHeroImageDuringJump];

}

}

}

 

- (void) updateScore:(ccTime)dt

{

    _score += 1;

    [scoreLayer.labelsetString:[NSStringstringWithFormat:@"%05dm", _score]];

    

    //increase difficulty every 200m run

    if (_score % kDifficultyScore == 0) {

        [selfincreaseDifficulty];

    }

}

 

 

 

-(void)changeHeroImageDuringJump 

{

[_herosetTextureRect:[[CCSpriteFrameCachesharedSpriteFrameCache

                           spriteFrameByName:@"snipe-jump.png"].rect];

}

 

- (void) increaseDifficulty

{

    platform.platformSpeed += kDifficultySpeed;

}

 

 

//register touch action

-(void) registerWithTouchDispatcher 

{

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

}

 

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

{

if (isJumping == NO && isGap == NO) {

//[_hero stopAllActions];

//[self changeHeroImageDuringJump];

isJumping = YES;

jumpVelocity = ccp(0, kJumpHigh);

[self schedule:@selector(jump:) interval:(1.0 / 60.0)];

        //[self schedule:@selector(jump:)];

}

returnYES;

}

 

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

{

if (jumpVelocity.y > kJumpShort) {

jumpVelocity = ccp(0, kJumpShort);

}

}

 

 

 

- (void)gameOver

{

    //NSLog(@"GAME OVER");

    _hero.visible = NO;

    [platform paused:YES];

    [_herostopAllActions];

    [selfunscheduleAllSelectors];

    

    GameOverScene *gameOverScene = [GameOverScene node];

    [[CCDirectorsharedDirector] replaceScene:gameOverScene];

}

 

 

 

- (void) initScore

{

    _score = 0;

    scoreLayer = [ScoreLayernode];

    [scoreLayer.labelsetString:[NSStringstringWithFormat:@"%05dm", _score]];

    [selfaddChild:scoreLayer];

    

    [self schedule:@selector(updateScore:) interval:(5.0 / 60.0)];

}

 

 

 

 

- (void) dealloc

{

    self.hero = nil;

self.runAction = nil;

    

    [self.hero release];

    [self.runAction release];

    [platform release];

    [super dealloc];

}

 

 

@end

转载于:https://www.cnblogs.com/eebb/archive/2013/01/29/2882202.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Cocos2d-x 是一个开源的跨平台游戏开发框架,支持 C++、Lua 和 JavaScript 等语言。以下是一个简单的飞机大战游戏的制作流程: 1. 创建一个新的 Cocos2d-x 项目,在命令行中使用以下命令: ``` cocos new MyGame -p com.your_company.mygame -l cpp -d /path/to/your/project ``` 其中,`MyGame` 是项目的名称,`com.your_company.mygame` 是项目的包名,`/path/to/your/project` 是项目的路径。 2. 在 `Classes` 文件夹下创建游戏场景类和游戏层类。游戏场景类负责管理游戏层,游戏层类负责绘制游戏界面和处理用户输入事件。可以参考以下代码: ```c++ class GameScene : public cocos2d::Scene { public: static cocos2d::Scene* createScene(); virtual bool init(); CREATE_FUNC(GameScene); }; class GameLayer : public cocos2d::Layer { public: virtual bool init(); void update(float delta); CREATE_FUNC(GameLayer); }; ``` 3. 在游戏层中添加背景图和玩家飞机。可以使用 `Sprite` 类来加载图片资源,并使用 `addChild()` 方法将其添加到层中。例如: ```c++ auto background = Sprite::create("background.png"); background->setPosition(visibleSize.width / 2, visibleSize.height / 2); addChild(background); player = Sprite::create("player.png"); player->setPosition(visibleSize.width / 2, player->getContentSize().height / 2); addChild(player); ``` 4. 实现玩家飞机的移动和射击功能。可以使用 `EventKeyboard` 类来监听键盘事件,并在 `update()` 方法中更新玩家飞机的位置和子弹的位置。例如: ```c++ void GameLayer::update(float delta) { // 移动玩家飞机 if (isKeyPressed(EventKeyboard::KeyCode::KEY_UP_ARROW)) { player->setPositionY(player->getPositionY() + 5.0f); } if (isKeyPressed(EventKeyboard::KeyCode::KEY_DOWN_ARROW)) { player->setPositionY(player->getPositionY() - 5.0f); } if (isKeyPressed(EventKeyboard::KeyCode::KEY_LEFT_ARROW)) { player->setPositionX(player->getPositionX() - 5.0f); } if (isKeyPressed(EventKeyboard::KeyCode::KEY_RIGHT_ARROW)) { player->setPositionX(player->getPositionX() + 5.0f); } // 发射子弹 if (isKeyPressed(EventKeyboard::KeyCode::KEY_SPACE)) { auto bullet = Sprite::create("bullet.png"); bullet->setPosition(player->getPositionX(), player->getPositionY() + player->getContentSize().height / 2); addChild(bullet); auto moveBy = MoveBy::create(1.0f, Vec2(0, visibleSize.height)); auto removeSelf = RemoveSelf::create(); auto sequence = Sequence::create(moveBy, removeSelf, nullptr); bullet->runAction(sequence); } } ``` 5. 添加敌机和碰撞检测功能。可以使用定时器来定期生成敌机,并使用 `Rect` 类来判断玩家飞机和子弹是否与敌机发生碰撞。例如: ```c++ void GameLayer::addEnemy(float delta) { auto enemy = Sprite::create("enemy.png"); float x = CCRANDOM_0_1() * visibleSize.width; enemy->setPosition(x, visibleSize.height + enemy->getContentSize().height / 2); addChild(enemy); auto moveBy = MoveBy::create(2.0f, Vec2(0, -visibleSize.height - enemy->getContentSize().height)); auto removeSelf = RemoveSelf::create(); auto sequence = Sequence::create(moveBy, removeSelf, nullptr); enemy->runAction(sequence); } void GameLayer::checkCollision() { for (auto enemy : enemies) { if (player->getBoundingBox().intersectsRect(enemy->getBoundingBox())) { // 碰撞处理 } for (auto bullet : bullets) { if (bullet->getBoundingBox().intersectsRect(enemy->getBoundingBox())) { // 碰撞处理 } } } } ``` 6. 最后,在游戏场景类的 `init()` 方法中添加游戏层、定时器和碰撞检测函数。例如: ```c++ bool GameScene::init() { if (!Scene::init()) { return false; } auto gameLayer = GameLayer::create(); addChild(gameLayer); schedule(schedule_selector(GameLayer::addEnemy), 1.0f); scheduleUpdate(); return true; } void GameLayer::update(float delta) { checkCollision(); } ``` 以上是一个简单的飞机大战游戏的制作流程,具体的实现细节还需要结合实际情况进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值