cocos2dx游戲--歡歡英雄傳說--添加攻擊按鈕

接下來添加攻擊按鈕用于執行攻擊動作。
同時修復了上一版移動時的bug。
修復后的Player::walkTo()函數:

void Player::walkTo(Vec2 dest)
{if (_seq)this->stopAction(_seq);auto curPos = this->getPosition();if (curPos.x > dest.x)this->setFlippedX(true);elsethis->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);
}

在MainScene::init()函數中添加了攻擊按鈕:

    auto attackItem = MenuItemImage::create("CloseNormal.png","CloseSelected.png",CC_CALLBACK_1(MainScene::attackCallback, this));attackItem->setPosition(Vec2(origin.x + visibleSize.width - attackItem->getContentSize().width/2 ,origin.y + attackItem->getContentSize().height/2));// create menu, it's an autorelease objectauto menu = Menu::create(attackItem, NULL);menu->setPosition(Vec2::ZERO);this->addChild(menu, 1);

增加了攻擊的回調函數:

void MainScene::attackCallback(Ref* pSender)
{_hero->stopAllActions();_hero->playAnimation("attack");
}

增加了Player::playAnimation()函數,執行了一次動作之后又回返回重復執行"stay"。

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 = 0; 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);
}

效果:

#ifndef __Player__
#define __Player__
#include "cocos2d.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);
private:PlayerType _type;std::string _name;int _animationNum = 5;float _speed;std::vector<int> _animationFrameNums;std::vector<std::string> _animationNames;Sequence* _seq;
};#endif
Player.h
#include "Player.h"
#include <iostream>bool Player::initWithPlayerType(PlayerType type)
{std::string sfName = "";std::string animationNames[5] = {"attack", "dead", "hit", "stay", "walk"};_animationNames.assign(animationNames,animationNames+5);switch (type){case PlayerType::HERO:{_name = "hero";sfName = "hero-stay0000.png";int animationFrameNums[5] = {10, 12, 15, 30, 24};_animationFrameNums.assign(animationFrameNums, animationFrameNums+5);_speed = 125;break;}case PlayerType::ENEMY:{_name = "enemy";sfName = "enemy-stay0000.png";int animationFrameNums[5] = {21, 21, 24, 30, 24};_animationFrameNums.assign(animationFrameNums, animationFrameNums+5);break;}}this->initWithSpriteFrameName(sfName);this->addAnimation();return true;
}
Player* Player::create(PlayerType type)
{Player* player = new Player();if (player && player->initWithPlayerType(type)){player->autorelease();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[0].c_str())->getCString());if (animation)return;for (int i = 0; i < _animationNum; i ++){auto animation = Animation::create();animation->setDelayPerUnit(1.0f / 10.0f);for (int j = 0; 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 = 0; 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 = 0; 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);elsethis->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);
}
Player.cpp
#ifndef __MainScene__
#define __MainScene__#include "cocos2d.h"
#include "Player.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;
};#endif
MainScene.h
#include "MainScene.h"
#include "FSM.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");Sprite* background = Sprite::create("images/background.png");background->setPosition(origin + visibleSize/2);this->addChild(background);//add player_hero = Player::create(Player::PlayerType::HERO);_hero->setPosition(origin.x + _hero->getContentSize().width/2, origin.y + visibleSize.height/2);this->addChild(_hero);//add enemy1_enemy = Player::create(Player::PlayerType::ENEMY);_enemy->setPosition(origin.x + visibleSize.width - _enemy->getContentSize().width/2, origin.y + visibleSize.height/2);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/2 ,origin.y + attackItem->getContentSize().height/2));// create menu, it's an autorelease objectauto menu = Menu::create(attackItem, NULL);menu->setPosition(Vec2::ZERO);this->addChild(menu, 1);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;
#endifDirector::getInstance()->end();#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)exit(0);
#endif
}bool MainScene::onTouchBegan(Touch* touch, Event* event)
{Vec2 pos = this->convertToNodeSpace(touch->getLocation());_hero->walkTo(pos);log("MainScene::onTouchBegan");return true;
}void MainScene::attackCallback(Ref* pSender)
{_hero->stopAllActions();_hero->playAnimation("attack");
}
MainScene.cpp

?

轉載于:https://www.cnblogs.com/moonlightpoet/p/5560715.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/255148.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/255148.shtml
英文地址,請注明出處:http://en.pswp.cn/news/255148.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Yii2.0 rules常用驗證規則

設置一個修改方法&#xff0c;但是save&#xff08;&#xff09;&#xff0c;沒有成功&#xff0c;數據修改失敗&#xff0c;查了好久&#xff0c;一般情況就是不符合rules規則&#xff0c;而我沒有設置rules規則&#xff0c;重新設置了一個不能為空&#xff0c;然后就修改成功…

HALCON示例程序gray_features.hdev提取灰度圖的不同特征(area_center_gray 、elliptic_axis_gray)

HALCON示例程序gray_features.hdev提取灰度圖的不同特征&#xff08;area_center_gray 、elliptic_axis_gray&#xff09; 示例程序源碼&#xff08;加注釋&#xff09; 讀入圖片 read_image (Image, ‘monkey’)二值化 threshold (Image, Region, 128, 255)分割連通域 conne…

Machine Vision Pixel Calibration~ ~ ~ ~ ~ ~ ~ ~ ~ ~

Artificial Intelligence and Robotics Research人工智能與機器人研究, 2014, 3, 25-33Published Online May 2014 in Hans. http://www.hanspub.org/journal/airrhttp://dx.doi.org/10.12677/airr.2014.32005

Ceph分布式存儲系統-性能測試與優化

測試環境 部署方案&#xff1a;整個Ceph Cluster使用4臺ECS&#xff0c;均在同一VPC中&#xff0c;結構如圖&#xff1a; 以下是 Ceph 的測試環境&#xff0c;說明如下&#xff1a; Ceph 采用 10.2.10 版本&#xff0c;安裝于 CentOS 7.4 版本中&#xff1b;系統為初始安裝&…

mysql考試總結

USE school; -- 班級表 CREATE TABLE class(cid TINYINT PRIMARY KEY AUTO_INCREMENT,caption VARCHAR(20) );INSERT INTO class(caption) VALUES("三年二班"),("一年三班"),("三年一班");SELECT * FROM class;-- 老師表 CREATE TABLE teacher(t…

反思

1.說明一下ArrayList和數組的區別&#xff0c;并且分別寫出初始化的語句&#xff1a; ArrayList:可以放不同的類型&#xff0c;長度不固定 數組&#xff1a;放同一類型&#xff0c;長度固定 數組的初始化語句&#xff1a;int []anew int []{}; ArrayList初始化語句&#xff1a;…

HALCON示例程序high.hdev使用不同方法提取區域

HALCON示例程序high.hdev使用不同方法提取區域 示例程序源碼&#xff08;加注釋&#xff09; 關于顯示類函數解釋 dev_close_window () read_image (Mreut, ‘mreut_y’) get_image_size (Mreut, Width, Height) dev_open_window (0, 0, Width, Height, ‘black’, WindowHan…

閱讀好書依然是提升自己的高效方法:兼以作者的身份告訴大家如何選擇書,以及高效學習的方法...

國內技術網站多如牛毛&#xff0c;質量高的網站也不少&#xff0c;博客園也算一個&#xff0c;各類文章數以百萬計&#xff0c;我隨便輸入一個關鍵字&#xff0c;比如Spring Cloud&#xff0c;都能看到大量的技術文章和教學視頻&#xff0c;我無意貶低技術文章和教學視頻的作用…

TCP/IP 協議簇的逐層封裝

在使用 TCP 協議的網絡程序中&#xff0c;用戶數據從產生到從網卡發出去一般要經過如下的逐層封裝過程&#xff1a; 從下往上看&#xff1a; 1&#xff09;鏈路層通過加固定長度的首部、尾部來封裝 IP 數據報(Datagram) 產生以太網幀(Frame)。 其中首部存在對封裝數據的…

【開源程序(C++)】獲取bing圖片并自動設置為電腦桌面背景

眾所周知&#xff0c;bing搜索網站首頁每日會更新一張圖片&#xff0c;張張漂亮&#xff08;額&#xff0c;也有一些不合我口味的&#xff09;&#xff0c;特別適合用來做電腦壁紙。 我們想要將bing網站背景圖片設置為電腦桌面背景的通常做法是&#xff1a; 上網&#xff0c;搜…

UIProgressView 圓角

里面外面都變成圓角 不用圖片 直接改變layer 重點是里面外面都是圓角哦 for (UIImageView * imageview in self.progress.subviews) { imageview.layer.cornerRadius 5; imageview.clipsToBounds YES; } 轉載于:https://www.cnblogs.com/huoran1120/p/5563991.html

HALCON示例程序holes.hdev孔洞提取

HALCON示例程序holes.hdev孔洞提取 示例程序源碼&#xff08;加注釋&#xff09; 關于顯示類函數解釋 read_image (Image, ‘progres’) get_image_size (Image, Width, Height) dev_close_window () dev_open_window (0, 0, Width, Height, ‘white’, WindowID) dev_set_co…

給實例動態增加方法VS給類動態增加方法

一、給實例綁定方法 object.method MethodType(method,object) >>>class Badbrains(): pass >>>def mocking(self): print(Brain\s Mocking) >>>b Badbrains() >>>from types import MethodType >>>b.mocking MethodType(moc…

一句DOS命令搞定文件合并

用Dos的copy命令實現&#xff1a; copy a.jsb.jsc.js abc.js /b 將 a.js b.js c.js 合并為一個 abc.js&#xff0c;最后的 /b 表示文件為二進位文件&#xff0c;copy 命令的其它參數可以在 cmd 里輸入 copy /? 學習 舉例&#xff1a;如果想要合并多個js文件到某個目錄下&#…

DataTables warning: Requested unknown parameter '0' from the data source for row '0'

問題&#xff1a;DataTables warning: Requested unknown parameter 0 from the data source for row 0 代碼&#xff1a; <script type"text/javascript">var data [{"Name":"UpdateBootProfile","Result":"PASS",&…

HALCON示例程序hull.hdev區域提取與凸度篩選

HALCON示例程序hull.hdev區域提取與凸度篩選 示例程序源碼&#xff08;加注釋&#xff09; 關于顯示類函數解釋 read_image (Hull, ‘hull’) get_image_size (Hull, Width, Height) dev_close_window () dev_open_window (0, 0, Width, Height, ‘black’, WindowID) dev_di…

我與Linux系統的交集

2019獨角獸企業重金招聘Python工程師標準>>> 一、初識Linux 第一次知道Linux還是在我剛進大學的時候&#xff0c;從開始聊QQ、玩斗地主的時候起我就是用的Windows&#xff0c;從Windows2000一直到Windows7&#xff0c;當時我已經完全習慣了使用Windows&#xff0c;而…

squid白名單

http_access deny all #取消注釋 http_access allow all --> http_access allow xxx_custom_ip#添加系統服務器IP白名單 acl xdaili_custom_ip src 60.191.4.xxx/32 acl xdaili_custom_ip src 139.196.210.xxx/32 acl xdaili_custom_ip src 139.196.172.xxx/32 acl xdail…

HALCON示例程序IC.hdev通過電路板元器件定位識別

HALCON示例程序IC.hdev通過電路板元器件定位識別 示例程序源碼&#xff08;加注釋&#xff09; 關于顯示類函數解釋 dev_close_window () read_image (Image, ‘ic’) get_image_size (Image, Width, Height) dev_open_window (0, 0, Width, Height, ‘black’, WindowID) de…

IP頭、TCP頭、UDP頭詳解以及定義

一、MAC幀頭定義 /*數據幀定義&#xff0c;頭14個字節&#xff0c;尾4個字節*/ typedef struct _MAC_FRAME_HEADER { char m_cDstMacAddress[6]; //目的mac地址 char m_cSrcMacAddress[6]; //源mac地址 short m_cType;      //上一層協議類型&#xff0c;如…