Reputation: 3
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?
Upvotes: 0
Views: 1282
Reputation: 1541
Array in use the boundingBox.
CGRect boundingBoxuser = user.boundingBox;
for (CCSprite *spritecoinleft in Arraycoinleft)
{
CGRect boundingBoxcoinleft = spritecoinleft.boundingBox;
if((CGRectIntersectsRect(boundingBoxcoinleft,boundingBoxuser)))
{
CCLOG(@"hi....!!");
}
}
Upvotes: 0
Reputation: 7720
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));
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]
Now child.boundingBox
and touchLocation
are in the same coordinate system.
Upvotes: 2