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

定义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包装目标Action
	bug->runAction(rotateBezierAct);


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值