实现物体的方向跟着拖拽的方向

实现物体的方向跟着拖拽的方向

bool Hero::touchBegin(Touch* touch,Event* event)
{
	auto target = static_cast<Sprite*>(event->getCurrentTarget());//得到对象

	if (target->getBoundingBox().containsPoint(touch->getLocation()))
	{
		target->setOpacity(200);
		return true;
	}
	return false;
}
void Hero::touchMoved(Touch* touch,Event* event)
{
	auto target = static_cast<Sprite*>(event->getCurrentTarget());
	
	static Point oldPosition = Point(-1,-1);
	static Point newPosition = Point(-1,-1);

	if (oldPosition.x ==-1)
	{
		oldPosition = target->getPosition();
	}
	else
	{
		oldPosition = newPosition;
		newPosition = target->getPosition();
		float width = newPosition.x - oldPosition.x;
		float height = newPosition.y - oldPosition.y;
		if (isActionDone)
		{
			float  radian;
			float angle;
				
			if (height>0&&width<0)
			{
				radian=atan(width/ height);//h弧度
				angle = (radian*360)/(2*3.141592);//化成角度了
			}
			if (height>0&&width==0)
			{
				angle = 0;
			}
			if (height>0&& width>0)
			{
				radian=atan(width/ height);//h弧度
				angle = (radian*360)/(2*3.141592);//化成角度了
			}
			if (height==0&&width >0)
			{
				angle = 90;
			}
			if (height<0&&width>0)
			{
				radian=atan( height/width);//h弧度
				angle = (radian*360)/(2*3.141592);//化成角度了
				angle =90- angle;
			}
			if (height<0&&width==0)
			{
				angle = 180;
			}
			if (height<0&&width<0)
			{
				radian=atan(width/ height);//h弧度
				angle = (radian*360)/(2*3.141592);//化成角度了
				angle+=180;
			}
			if (height==0&&width<0)
			{
				angle = 270;
			}
			CallFunc * funcall= CallFunc::create(this, callfunc_selector(Hero::actionDone));
			FiniteTimeAction* actionRotateBy= RotateTo::create(0.1,angle);
			FiniteTimeAction* task = Sequence::create(actionRotateBy,funcall, NULL);
			runAction(task);
			isActionDone = false;
		}
	}

	target->setPosition(target->getPosition() + touch->getDelta());//防出界
	if (target->getPositionX()<0)
	{
		target->setPositionX(0);
	}
	if (target->getPositionX()>Director::getInstance()->getWinSize().width)
	{
		target->setPositionX(Director::getInstance()->getWinSize().width);
	}
	if (target->getPositionY()<0)
	{
		target->setPositionY(0);
	}
	if (target->getPositionY()>Director::getInstance()->getWinSize().height)
	{
		target->setPositionY(Director::getInstance()->getWinSize().height);
	}
}
void Hero::touchEnded(Touch* touch,Event* event)
{
	auto target = static_cast<Sprite*>(event->getCurrentTarget());
	target->setOpacity(255);
}


你可能感兴趣的:(实现物体的方向跟着拖拽的方向)