android cocos2d动作自定义

来源:互联网 发布:worktile个人版 mac 编辑:程序博客网 时间:2024/05/13 11:23

我们创建了一个精灵之后,这个精灵一般不是静止不动的,而是运动的,然后系统自带的动作有时不能完全满足我们的需求,这时我们就需要对动作进行自定义,这里我写了一个简单的抛物线运动,不说了,上代码吧

CustomAction.h文件,需要注意的是我们进行开发的类是继承自CCActionInterval的,有限时间运动

#ifndef FREE_FALL_H#define FREE_FALL_H#include "cocos2d.h"#define LEFT  0#define RIGHT 1class ThrowBall: public cocos2d::CCActionInterval {private:  float  m_h_speed;//该抛物运动的水平速度  int m_move_times;  int m_direction;//向左或者向右  cocos2d::CCSize m_size;//当前屏幕大小public:virtual void update(float time);public:static ThrowBall * create(float t,float speed,int);bool init(float t,float speed,int);void checkStop();};#endif

CustomAction.cpp文件如下

#include "AppMacros.h"#include "CustomAction.h"USING_NS_CC;ThrowBall* ThrowBall::create(float t,float speed,int direction){ThrowBall *pRet = new ThrowBall();pRet->init(t,speed,direction);pRet->autorelease();return pRet;}bool ThrowBall::init(float t,float speed,int direction){if(CCActionInterval::initWithDuration(t)){m_h_speed = speed;m_direction = direction;m_move_times = 0;m_size=CCDirector::sharedDirector()->getVisibleSize();return true;}return false;}void ThrowBall::checkStop(){CCPoint pGL = CCDirector::sharedDirector()->convertToGL(m_pTarget->getPosition());if ((pGL.x+15) > (m_size.width)) {m_pTarget->stopAllActions();} else if (pGL.x < 15) {m_pTarget->stopAllActions();} else if (pGL.y < 15) {m_pTarget->stopAllActions();} elseif (pGL.y +15> (m_size.height)) {m_pTarget->stopAllActions();}}void ThrowBall::update(float time){m_move_times++;//每帧刷新频率时间是float y=m_pTarget->getPosition().y-m_move_times*(0.5*10*(CCDirector::sharedDirector()->getAnimationInterval()*m_move_times)*(m_move_times*CCDirector::sharedDirector()->getAnimationInterval()));float x=m_pTarget->getPosition().x;if(m_direction==RIGHT){//向右x自增x+=m_h_speed*CCDirector::sharedDirector()->getAnimationInterval()*m_move_times;}else{x-=m_h_speed*CCDirector::sharedDirector()->getAnimationInterval()*m_move_times;}//开始检测是否已经在屏幕边缘m_pTarget->setPosition(ccp(x,y));checkStop();}
我们需要注意的两个函数是update和checkStop,update函数是由系统调用的函数,该函数在每当需要帧刷新时进行调用,而帧的刷新时间是CCDirector::sharedDirector()->getAnimationInterval()

我们通过记录m_move_times的次数,来计算总的运动时间,通过该运动时间来进行新的Sprite的定位。我们通过计算得到新的Sprite位置信息,然后根据m_pTarget,即动作Node,调用setPosition来进行调用。

而checkStop,则是检测目标是否移动到了屏幕边缘,如果到了边缘则停止移动,m_pTarget->stopAllActions();

好了本次讲解结束。

0 0
原创粉丝点击