【问题标题】:ccsprite rotation offset when it rotates to touch locationccsprite旋转到触摸位置时的旋转偏移
【发布时间】:2013-07-06 12:57:44
【问题描述】:

我正在旋转一个精灵 (rect) 以面对屏幕上的触摸位置。代码有效,但有几度的偏移量,精灵越垂直,偏移量越大。我在下面添加了一张图片,非常清楚地说明了我的问题。

红点是我在photoshop中添加的触摸位置,用来显示偏移问题。 所以唯一可见的精灵是矩形(IE rect)。

当我处于 90 度角时,偏移最为明显。然后越靠近中心,它又逐渐消失。

我怎样才能使精灵准确地面向触摸位置? 或者我该如何纠正这个偏移量?

- (void) ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{

    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:[touch view]];
    location = [[CCDirector sharedDirector] convertToGL:location];

    float angle = atan2f(location.y-rect.position.y, location.x-rect.position.y);
    angle = CC_RADIANS_TO_DEGREES(angle);
    angle *=-1;

    rect.rotation = angle;
    float distance = sqrtf(pow((location.x-rect.position.x), 2)+pow(location.y-rect.position.y, 2));
    rect.scaleX = distance;

}

【问题讨论】:

  • 什么是矩形?它与您展示的 2 个精灵有什么关系?
  • rect 是精灵。我在 Photoshop 中添加的红色圆圈以显示触摸位置与矩形角度的关系。

标签: ios objective-c cocos2d-iphone trigonometry


【解决方案1】:

该不该这样声明:

float angle = atan2f(location.y-rect.position.y, location.x-rect.position.y);

改为:

float angle = atan2f(location.y-rect.position.y, location.x-rect.position.x);

?

此外,您的问题可能与您的 sprite anchorPoint 有关。

默认情况下,精灵的锚点是(0.5, 0.5),即精灵的中心。这是作为精灵参考的点;例如,您的精灵的position 是锚点位置;如果您应用旋转角度,您的精灵将围绕锚点旋转。

所以,您可以尝试像这样设置您的精灵锚点:

rect.anchorPoint = ccp(0,0);

或

rect.anchorPoint = ccp(1,1);

这应该会更好。

或者,您可以保留现在的锚点,但相对于您的视图中心(我猜这是一个固定点)进行数学运算:

 float angle = atan2f(location.y - viewCenter.y, location.x - viewCenter.x);

【讨论】:

  • aaaargh 我犯了一个多么愚蠢的错误。 atan2f(location.y-rect.position.y, location.x-rect.position.x); 是问题所在。代码现在工作正常。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-17
  • 1970-01-01
  • 1970-01-01
  • 2016-02-12
相关资源
最近更新 更多