移动图层后,精灵边界框显示错误的位置 [英] A sprite bounding box shows wrong position after moving the layer
问题描述
我刚刚开始学习一些cocos2d,这个问题困扰了我很长一段时间。基本上我想要做的是通过检查触摸着陆在sprite边界框使用 ccTouchBegan
和 ccTouchMoved
。
I have just started to learn some cocos2d and this issue had bothered me for quite a while. Basically what i am trying to do is to move a sprite in a layer by checking whether the touch landed on the sprite bounding box using ccTouchBegan
and ccTouchMoved
.
一切都正常工作,直到我移动图层,其中包括许多其他精灵,也比屏幕尺寸更大。在我移动图层之后,精灵的边界框位于与精灵图像显示的位置不同的位置。
Everything worked until I moved the layer, which include many other sprite and is also lager than the screen size. After I moved the layer the sprite's bounding box is at a different position as where the sprite image shows. Had anyone experienced similar issue before?
推荐答案
sprite的 boundingBox
相对于sprite的父坐标系。如果您移动,旋转或缩放父对象,则子对象仍将具有相同的 boundingBox
。您可以将其转换为另一个坐标系。如果父对象只被移动(不旋转或缩放),只需要改变 boundingBox c的
origin
code>:
A sprite's boundingBox
is always relative to the sprite's parent's coordinate system. If you move, rotate or scale the parent, the child will still have the same boundingBox
. You can convert that to another coordinate system. If the parent has only been moved (not rotated or scaled) you can convert to the world coordinate system just by changing the origin
of the boundingBox
:
CGRect boundingBox = child.boundingBox;
boundingBox.origin = [child.parent convertToWorldSpace:boundingBox.origin];
NSLog(@"%@", NSStringFromCGRect(boundingBox));
如果缩放父对象的尺寸,如果父旋转它变得相当复杂,因为孩子的boundingBox的比例和宽高比可以改变。如果所有你想做的是测试是否在boundigBox中发生触摸,将触摸位置转换为孩子的父坐标系统:
If the parent is scaled the size of the child's boundingBox changes accordingly. If the parent is rotated it gets quite complicated because both scale and aspect ratio of the child's boundingBox can change. If all you want to do is test if a touch occurred in the boundigBox, convert the touch location to the child's parent's coordinate system:
CGPoint touchLocation = [child.parent convertToNodeSpace:touchWorldLocation]
现在 boundingBox
和 touchLocation
在同一坐标系中。
Now child.boundingBox
and touchLocation
are in the same coordinate system.
这篇关于移动图层后,精灵边界框显示错误的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!