如何旋转对象指向cocos2d中的另一个点?

时间:2014-07-16 23:28:38

标签: ios objective-c cocos2d-iphone

我希望让CCSprite旋转并指向屏幕上用户点按的任何位置。我的点击检测工作正常。这是我的轮换代码:

double delX = touchPoint.x - _hero.position.x;
double delY = touchPoint.y - _hero.position.y;
int theta = atan(delY/delX);

theta = theta * (180/M_PI); // conversion to degrees
if (theta < 0)
{
    theta = abs(theta) + 90;
}
theta = abs(theta);

theta += 180;


bullet.rotation = -1*theta; // to turn right instead of left, the -1

子弹位于_hero.position,而touchPoint是用户点击的点。有任何想法吗?

编辑:谢谢,flowmachine1!除了某些原因它是向后的,所以我只是将这段代码添加到你的答案中:

if (angle<90)
{
    angle = abs(90-angle) + 90;
}else if (angle >90)
{
    angle = 90 - abs(90-angle);
} 

然后它奏效了!谢谢!

1 个答案:

答案 0 :(得分:0)

也许是这样的?

pos1 = touchPosition;
pos2 = spritePosition;

double angle = atan2(pos1.y - pos2.y, pos1.x - pos2.x) * 180 / M_PI;

sprite.rotation = angle;