Cocos2d-x 随运动方向转变图片方向实现方式

来源:互联网 发布:淘宝商务模式分析 编辑:程序博客网 时间:2024/05/16 17:57
定义RotateWithAction类,重写step方法,在每帧刷新前调整图片角度为前进路线的切线:RotateWithAction.h
#pragma once#include "cocos2d.h"USING_NS_CC;class RotateWithAction:public cocos2d::CCActionInterval{public:CCObject* copyWithZone(CCZone* pZone);RotateWithAction(void);~RotateWithAction(void);static RotateWithAction* create(CCActionInterval* action);virtual void startWithTarget(CCNode *pTarget);bool initWithAction(CCActionInterval* pAction);bool isDone();void step(float dt);protected:void RotateWithAction::SetInnerAction(CCActionInterval* pAction);CCNode* pInnerTarget;CCActionInterval* pInnerAction;};


RotateWithAction.cpp
RotateWithAction::~RotateWithAction(void){CC_SAFE_RELEASE(pInnerAction);}RotateWithAction* RotateWithAction::create( CCActionInterval* pAction ){RotateWithAction* action = new RotateWithAction();if(action && action->initWithAction(pAction)){action->autorelease();return action;}CC_SAFE_DELETE(action);return NULL;}bool RotateWithAction::initWithAction( CCActionInterval* pAction ){pAction->retain();pInnerAction=pAction;return true;}void RotateWithAction::startWithTarget( CCNode *pTarget ){pInnerTarget=pTarget;CCAction::startWithTarget(pTarget);pInnerAction->startWithTarget(pTarget);}bool RotateWithAction::isDone(){return pInnerAction->isDone();}//关键代码 void RotateWithAction::step( float dt ){CCPoint prePos=pInnerTarget->getPosition();pInnerAction->step(dt);CCPoint curPos=pInnerTarget->getPosition();float degree=atan2((curPos.x-prePos.x),(curPos.y-prePos.y));//求本帧位置与前帧位置相连形成的夹角。atan2获得弧度值degree=degree/3.14159f*180;//根据弧度求出角度pInnerTarget->setRotation(degree); //设置图片旋转角度}void RotateWithAction::SetInnerAction( CCActionInterval* pAction ){if (pInnerAction!=pAction){CC_SAFE_RELEASE(pInnerAction);pInnerAction=pAction;CC_SAFE_RETAIN(pInnerAction);}}CCObject* RotateWithAction::copyWithZone( CCZone* pZone ){CCZone* pNewZone=NULL;RotateWithAction* pCopy=NULL;if(pZone&&pZone->m_pCopyObject){pCopy=(RotateWithAction*)(pZone->m_pCopyObject);}else{pCopy=new RotateWithAction();pZone=pNewZone=new CCZone(pCopy);}CCActionInterval::copyWithZone(pZone);pCopy->initWithAction(dynamic_cast<CCActionInterval*>(pInnerAction->copy()->autorelease()));CC_SAFE_DELETE(pNewZone);return pCopy;}

使用RotateWithAction:

CCActionInterval* bezierAct = CCBezierTo::create(5,bezier);RotateWithAction* rotateBezierAct = RotateWithAction::create(bezierAct);//用RotateWithAction包装目标Actionbug->runAction(rotateBezierAct);


原创粉丝点击