最近在搞连线的游戏,之前的博客里也提到了用DrawNode画粗线的方法。(http://blog.csdn.net/no99es/article/details/38823673)
线画出来之后,就想用绳子代替它,由于三角函数忘光了,耽误了时间,今天终于搞完了,记录下来。
使用的绳子图片:
网上找的,横向的绳子。
原理:
用setTextureRect方法,显示指定长度的绳子,然后根据触摸点坐标,进行旋转。
下面贴出两段关键代码:
/*
*添加触摸监听
*/
auto myListener = EventListenerTouchOneByOne::create();
//myListener->setSwallowTouches(true);
myListener->onTouchBegan = CC_CALLBACK_2(LineTest::TouchBegan,this);
myListener->onTouchMoved = CC_CALLBACK_2(LineTest::TouchMoved,this);
myListener->onTouchEnded = CC_CALLBACK_2(LineTest::TouchEnded,this);
_eventDispatcher->addEventListenerWithSceneGraPHPriority(myListener,this);
触摸方法里,Began跟Moved代码差不多,大家自由发挥~~
bool LineTest::TouchBegan(Touch* touch,Event* event)
{
spline->setVisible(true);
//长度,触摸点到屏幕中心的距离
int texturehight = sqrt(pow((touch->getLocation().x - visibleSize.width / 2 + origin.x),2) + pow((touch->getLocation().y - visibleSize.height / 2 + origin.y),2));
spline->setTextureRect(Rect(0,texturehight,40));
//旋转
float x = touch->getLocation().x - visibleSize.width / 2.0f + origin.x;
float y = touch->getLocation().y - visibleSize.height / 2.0f + origin.y;
float f = GetRotationDegree(x,y);
spline->setRotation(f);
return true;
}
///////////////////获取旋转角度//////////////
float LineTest::GetRotationDegree(float x,float y)
{
if (x == 0 && y == 0)
{
return 0;
}
float result;
if (x == 0&&y>0)
{
return 90;
}
else if (x == 0 && y < 0)
{
return 180;
}
else
{
float temp = y / x;
result = - atan(temp) * 180.0 / M_PI;
if (x>0)
{
return result;
}
else
{
return result+180;
}
}
}
效果:
原文链接:https://www.f2er.com/cocos2dx/347097.html