cocos2dx游戏--欢欢英雄传说--为敌人添加移动和攻击动作
这里主要为敌人添加了一个移动动作和攻击动作。
移动动作是很简略的我动他也动的方式。
攻击动作是很简单的我打他也打的方式。
效果:
代码:
#ifndef __Progress__
#define __Progress__
#include "cocos2d.h"
USING_NS_CC; class Progress : public Sprite
{
public:
bool init(const char* background, const char* fillname);
/*
the inputs are SpriteFrame Names.
they should be loaded into SpriteFrameCache before calling this.
*/
static Progress* create(const char* background, const char* fill); void setFill(ProgressTimer* fill){_fill=fill;} void setProgress(float percentage){_fill->setPercentage(percentage);}
float getProgress() { return _fill->getPercentage(); } private:
ProgressTimer* _fill;
};
#endif
Progress.h
#include "Progress.h" bool Progress::init(const char* background, const char* fillname)
{
this->initWithSpriteFrameName(background);
ProgressTimer* fill = ProgressTimer::create(Sprite::createWithSpriteFrameName(fillname));
this->setFill(fill);
this->addChild(fill); fill->setType(ProgressTimer::Type::BAR);
fill->setMidpoint(Point(,0.5));
fill->setBarChangeRate(Point(1.0, ));
fill->setPosition(this->getContentSize()/);
fill->setPercentage();
return true;
} Progress* Progress::create(const char* background, const char* fillname)
{
Progress* progress = new Progress();
if(progress && progress->init(background,fillname))
{
progress->autorelease();
return progress;
}
else
{
delete progress;
progress = NULL;
return NULL;
}
}
Progress.cpp
#ifndef __Player__
#define __Player__
#include "cocos2d.h"
#include "Progress.h" USING_NS_CC; class Player : public Sprite
{
public:
enum PlayerType
{
HERO,
ENEMY
};
bool initWithPlayerType(PlayerType type);
static Player* create(PlayerType type);
void addAnimation();
void playAnimationForever(std::string animationName);
void playAnimation(std::string animationName);
void walkTo(Vec2 dest);
Sequence* getSeq() { return _seq; }
void getHit();
void autoDoAction(Player* hero);
void autoAttack(Player* hero);
Progress* getProgress() { return _progress; }
private:
PlayerType _type;
std::string _name;
int _animationNum = ;
float _speed;
std::vector<int> _animationFrameNums;
std::vector<std::string> _animationNames;
Sequence* _seq;
Progress* _progress;
bool _isShowBar;
}; #endif
Player.h
#include "Player.h"
#include <iostream> bool Player::initWithPlayerType(PlayerType type)
{
std::string sfName = "";
std::string animationNames[] = {"attack", "dead", "hit", "stay", "walk"};
_animationNames.assign(animationNames,animationNames+);
switch (type)
{
case PlayerType::HERO:
{
_name = "hero";
sfName = "hero-stay0000.png";
_isShowBar = false;
int animationFrameNums[] = {, , , , };
_animationFrameNums.assign(animationFrameNums, animationFrameNums+);
_speed = ;
break;
}
case PlayerType::ENEMY:
{
_name = "enemy";
sfName = "enemy-stay0000.png";
_isShowBar = true;
int animationFrameNums[] = {, , , , };
_animationFrameNums.assign(animationFrameNums, animationFrameNums+);
_speed = ;
break;
}
}
this->initWithSpriteFrameName(sfName);
this->addAnimation(); auto size = this->getContentSize();
_progress = Progress::create("small-enemy-progress-bg.png","small-enemy-progress-fill.png");
_progress->setPosition( size.width/, size.height + _progress->getContentSize().height/);
this->addChild(_progress);
if(!_isShowBar)
{
_progress->setVisible(false);
} return true;
}
Player* Player::create(PlayerType type)
{
Player* player = new Player();
if (player && player->initWithPlayerType(type))
{
player->autorelease();
player->setAnchorPoint(Vec2(0.5, ));
return player;
}
else
{
delete player;
player = NULL;
return NULL;
}
}
void Player::addAnimation()
{
auto animation = AnimationCache::getInstance()->getAnimation(String::createWithFormat("%s-%s", _name.c_str(),
_animationNames[].c_str())->getCString());
if (animation)
return;
for (int i = ; i < _animationNum; i ++)
{
auto animation = Animation::create();
animation->setDelayPerUnit(1.0f / 10.0f);
for (int j = ; j < _animationFrameNums[i]; j ++)
{
auto sfName = String::createWithFormat("%s-%s%04d.png", _name.c_str(), _animationNames[i].c_str(), j)->getCString();
animation->addSpriteFrame(SpriteFrameCache::getInstance()->getSpriteFrameByName(sfName));
if (!animation)
log("hello ha ha");
}
AnimationCache::getInstance()->addAnimation(animation, String::createWithFormat("%s-%s", _name.c_str(),
_animationNames[i].c_str())->getCString());
}
}
void Player::playAnimationForever(std::string animationName)
{
auto str = String::createWithFormat("%s-%s", _name.c_str(), animationName.c_str())->getCString();
bool exist = false;
for (int i = ; i < _animationNum; i ++) {
if (animationName == _animationNames[i])
{
exist = true;
break;
}
}
if (exist == false)
return;
auto animation = AnimationCache::getInstance()->getAnimation(str);
auto animate = RepeatForever::create(Animate::create(animation));
this->runAction(animate);
} void Player::playAnimation(std::string animationName)
{
auto str = String::createWithFormat("%s-%s", _name.c_str(), animationName.c_str())->getCString();
bool exist = false;
for (int i = ; i < _animationNum; i ++) {
if (animationName == _animationNames[i])
{
exist = true;
break;
}
}
if (exist == false)
return;
auto animation = AnimationCache::getInstance()->getAnimation(str);
auto func = [&]()
{
this->stopAllActions();
this->playAnimationForever("stay");
_seq = nullptr;
};
auto callback = CallFunc::create(func);
auto animate = Sequence::create(Animate::create(animation), callback,NULL);
this->runAction(animate);
} void Player::walkTo(Vec2 dest)
{
if (_seq)
this->stopAction(_seq);
auto curPos = this->getPosition();
if (curPos.x > dest.x)
this->setFlippedX(true);
else
this->setFlippedX(false);
auto diff = dest - curPos;
auto time = diff.getLength() / _speed;
auto moveTo = MoveTo::create(time, dest);
auto func = [&]()
{
this->stopAllActions();
this->playAnimationForever("stay");
_seq = nullptr;
};
auto callback = CallFunc::create(func);
this->stopAllActions();
this->playAnimationForever("walk");
_seq = Sequence::create(moveTo, callback, nullptr); this->runAction(_seq);
} void Player::getHit()
{
float blood = _progress->getProgress();
if (_name == "hero")
blood -= ;
else
blood -= ;
_progress->setProgress(blood);
log(String::createWithFormat("hit now blood is %f", blood)->getCString());
if (blood <= )
{
log(String::createWithFormat("%s is dead.", _name.c_str())->getCString());
auto func = [&]()
{
this->stopAllActions();
this->playAnimation("dead");
};
auto callback = CallFunc::create(func);
_seq = Sequence::create(callback, nullptr);
this->runAction(_seq);
this->_progress->setVisible(false);
this->setVisible(false);
return;
}
} void Player::autoDoAction(Player* hero) // just for _enemy
{
Vec2 dest = hero->getPosition();
if (_seq)
this->stopAction(_seq);
auto curPos = this->getPosition();
if (curPos.x > dest.x)
this->setFlippedX(true);
else
this->setFlippedX(false);
auto diff = dest - curPos;
if (diff.x > ) diff.x -= ;
else diff.x += ;
if (diff.y > ) diff.y -= ;
else diff.y += ;
auto time = diff.getLength() / _speed;
auto moveTo = MoveTo::create(time, dest);
auto func = [&]()
{
this->stopAllActions();
this->playAnimationForever("stay");
_seq = nullptr;
};
auto callback = CallFunc::create(func);
this->stopAllActions();
this->playAnimationForever("walk");
_seq = Sequence::create(moveTo, callback, nullptr); this->runAction(_seq);
} void Player::autoAttack(Player* hero) // just for _enemy
{
float blood = _progress->getProgress();
if (blood <= )
return;
Vec2 del = this->getPosition() - hero->getPosition();
if (del.length() <= )
{
this->playAnimation("attack");
hero->getHit();
}
}
Player.cpp
#ifndef __MainScene__
#define __MainScene__ #include "cocos2d.h"
#include "Player.h"
#include "Progress.h" USING_NS_CC; class MainScene : public cocos2d::Layer
{
public:
static cocos2d::Scene* createScene();
virtual bool init();
void menuCloseCallback(cocos2d::Ref* pSender);
CREATE_FUNC(MainScene);
bool onTouchBegan(Touch* touch, Event* event);
void attackCallback(Ref* pSender);
private:
Player* _hero;
Player* _enemy;
EventListenerTouchOneByOne* _listener_touch;
Progress* _progress;
}; #endif
MainScene.h
#include "MainScene.h" Scene* MainScene::createScene()
{
auto scene = Scene::create();
auto layer = MainScene::create();
scene->addChild(layer);
return scene;
}
bool MainScene::init()
{
if ( !Layer::init() )
{
return false;
}
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin(); SpriteFrameCache::getInstance()->addSpriteFramesWithFile("images/role.plist","images/role.png");
SpriteFrameCache::getInstance()->addSpriteFramesWithFile("images/ui.plist","images/ui.pvr.ccz"); Sprite* background = Sprite::create("images/background.png");
background->setPosition(origin + visibleSize/);
this->addChild(background); //add player
_hero = Player::create(Player::PlayerType::HERO);
_hero->setPosition(origin.x + _hero->getContentSize().width/, origin.y + visibleSize.height/);
this->addChild(_hero); //add enemy1
_enemy = Player::create(Player::PlayerType::ENEMY);
_enemy->setPosition(origin.x + visibleSize.width - _enemy->getContentSize().width/, origin.y + visibleSize.height/);
this->addChild(_enemy); _hero->playAnimationForever("stay");
_enemy->playAnimationForever("stay"); _listener_touch = EventListenerTouchOneByOne::create();
_listener_touch->onTouchBegan = CC_CALLBACK_2(MainScene::onTouchBegan,this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(_listener_touch, this); auto attackItem = MenuItemImage::create(
"CloseNormal.png",
"CloseSelected.png",
CC_CALLBACK_1(MainScene::attackCallback, this)); attackItem->setPosition(Vec2(origin.x + visibleSize.width - attackItem->getContentSize().width/ ,
origin.y + attackItem->getContentSize().height/)); // create menu, it's an autorelease object
auto menu = Menu::create(attackItem, NULL);
menu->setPosition(Vec2::ZERO);
this->addChild(menu, ); _progress = Progress::create("player-progress-bg.png","player-progress-fill.png");
_progress->setPosition(_progress->getContentSize().width/, this->getContentSize().height - _progress->getContentSize().height/);
this->addChild(_progress); return true;
}
void MainScene::menuCloseCallback(cocos2d::Ref* pSender)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
MessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert");
return;
#endif Director::getInstance()->end(); #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
exit();
#endif
} bool MainScene::onTouchBegan(Touch* touch, Event* event)
{
Vec2 pos = this->convertToNodeSpace(touch->getLocation());
_hero->walkTo(pos);
log("MainScene::onTouchBegan");
_enemy->autoDoAction(_hero);
return true;
} void MainScene::attackCallback(Ref* pSender)
{
_hero->stopAllActions();
_hero->playAnimation("attack");
Vec2 del = _hero->getPosition() - _enemy->getPosition();
float distance = del.length();
log(String::createWithFormat("distance == %f", distance)->getCString());
if (distance <= 100.0) {
_enemy->getHit();
}
_enemy->autoAttack(_hero);
_progress->setProgress(_hero->getProgress()->getProgress());
}
MainScene.cpp
------------华丽的分割线------------
最近工作上出了一点事情。可能暂时就写到这里了。希望以后有机会能够再补上接下来的内容。
参考教程:http://www.cocos.com/doc/tutorial/lists?id=85
项目github地址:https://github.com/moonlightpoet/HuanHero
cocos2dx游戏--欢欢英雄传说--为敌人添加移动和攻击动作的更多相关文章
- cocos2dx游戏--欢欢英雄传说--添加游戏背景
经过一段时间的学习cocos2dx,接下来我想要实践开发一个小游戏,我把它命名为“欢欢英雄传说”,项目名将取为HuanHero.环境:cocos2dx环境:cocos2d-x 3.11.1IDE:Co ...
- cocos2dx游戏--欢欢英雄传说--添加攻击按钮
接下来添加攻击按钮用于执行攻击动作.同时修复了上一版移动时的bug.修复后的Player::walkTo()函数: void Player::walkTo(Vec2 dest) { if (_seq) ...
- cocos2dx游戏--欢欢英雄传说--添加人物
接下来需要导入精灵帧资源,因为之前下载了TexturePacker,然后通过TexturePacker的"Publish sprite sheet"方法可以生成一个.pvr.ccz ...
- cocos2dx游戏--欢欢英雄传说--添加动作
添加完人物之后接着给人物添加上动作.我们为hero添加4个动作:attack(由3张图片构成),walk(由2张图片构成),hit(由1张图片构成),dead(由1张图片构成):同样,为enemy添加 ...
- cocos2dx游戏--欢欢英雄传说--添加触摸响应
主要的调整就是将HelloWorldScene改成了MainSecne,然后将Player作为了MainScene的私有成员变量来处理.修改了人物图片,使用了网上找到的三国战纪的人物素材代替我之前画的 ...
- cocos2dx游戏--欢欢英雄传说--添加血条
用一个空血槽图片的Sprite做背景,上面放一个ProgressTimer, 通过设置ProgressTimer的进度来控制血条的长短.建立一个Progress类来实现.Progress.h: #if ...
- 转载:Cocos2D-x 游戏接入 Windows 设备所需做的六件事
原文地址:http://msopentech.com/zh-hans/blog/2014/05/09/cocos2d-x-%E6%B8%B8%E6%88%8F%E6%8E%A5%E5%85%A5-wi ...
- Cocos2dx游戏开发系列笔记13:一个横版拳击游戏Demo完结篇
懒骨头(http://blog.csdn.net/iamlazybone QQ:124774397 ) 写下这些东西的同时 旁边放了两部电影 周星驰的<还魂夜> 甄子丹的<特殊身份& ...
- Android Cocos2d-x游戏集成友盟社会化组件分享功能
最近在帮助开发者集成友盟社会化组件的过程中,发现游戏的集成过程遇到一些困难,而Cocos2d-x具有较好的代表性,因此整理了一篇关于Android Cocos2d-x游戏集成友盟社会化组件指南,由于本 ...
随机推荐
- ioss使用xcode常用快捷键
// command+r 运行 //command+.停止 // command+shift+y 弹出打印区 // command+z 回退 //command+shift+z 前进 // comma ...
- 基于CSS3和jQuery实现的3D相册
天我们再来看一款HTML5 3D相册浏览应用,图片可以手动播放,也可以自动播放,效果非常震撼,赶紧把这款HTML5 3D相册分享给你的朋友吧. 在线预览 源码下载 实现的代码: <div c ...
- Thrift RPC框架介绍
u 简介 Thrift是一种开源的跨语言的RPC服务框架.Thrift最初由facebook公司开发的,在2007年facebook将其提交apache基金会开源了.对于当时的facebook来说创造 ...
- C语言 · 9-1九宫格
算法提高 9-1九宫格 时间限制:1.0s 内存限制:256.0MB 问题描述 九宫格.输入1-9这9个数字的一种任意排序,构成3*3二维数组.如果每行.每列以及对角线之和都相等,打 ...
- NIO与传统IO的区别<转>
传统的socket IO中,需要为每个连接创建一个线程,当并发的连接数量非常巨大时,线程所占用的栈内存和CPU线程切换的开销将非常巨大.使用NIO,不再需要为每个线程创建单独的线程,可以用一个含有限数 ...
- yarn 用户导致的被挖矿 启用Kerberos认证功能,禁止匿名访问修改8088端口
用户为dr.who,问下内部使用人员,都没有任务在跑: 结论: 恭喜你,你中毒了,攻击者利用Hadoop Yarn资源管理系统REST API未授权漏洞对服务器进行攻击,攻击者可以在未授权的情况下远程 ...
- iOS边练边学--xib文件初使用
一.Xib和storyboard对比 *共同点: 1>都用来描述软件界面 2>都用Interface Builder工具来编辑 3>本质都是转换成代码去创建控件 *不同点 1> ...
- 01 Developing Successful Oracle Application
本章提要-------------------------------本章是概述性章节1. 介绍了了解数据库内部结构对于开发的重要性2. 介绍了如何才能开发好的数据库应用程序------------- ...
- @Configuration和@Bean的用法和理解
spring Boot提倡约定优于配置,如何将类的生命周期交给spring 1.第一种自己写的类,Controller,Service. 用@controller @service即可 2.第二种,集 ...
- SSH远程登录其他机器
常用格式:ssh [-l login_name] [-p port] [user@]hostname更详细的可以用ssh -h查看. 不指定用户: ssh 192.168.0.11 指定用户: ssh ...