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.mzph.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;如…