android cocos2d动作自定义

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

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

#ifndef FREE_FALL_H
#define FREE_FALL_H
#include "cocos2d.h"
#define LEFT  0
#define RIGHT 1
class 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();
	} else	if (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
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

世纪殇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值