Texture position of a sprite shifted [cocos2d v3]

225 Views Asked by At

I've been struggling for days with that problem: I have CCNode >> StateComponent and in the StateComponent I have a CCSprite as an attribute and add it as a child in StateComponent. When I set the position of an StateComponent object and NOT of the sprite, the bounding box of the StateComponent object appears at the right place. The default values for a sprite position are set on (0,0). The bounding box of the sprite appears at (0,0) but the sprite texture is shifted from (0,0). I add the StateComponent object afterwards to a CCScene.

Could maybe someone help me with advice: how can I set the sprite position so that the texture and bounding box appears at the same position as the StateComponent object? Later I'd like to detect if there is a touch on the node(sprite) and then rotate the node with the sprite.

Any help would be really appreciated!!!

@interface StateComponent : CCNode {

}
@end

@implementation StateComponent

-(instancetype) initWithGestureStatewithSprite:(CCSprite*) sprite andPosition: (CGPoint) spritePosition RelativeAngle:(float) angle {

    self = [super init];

    if (!self) {
        return nil;
    }

    self.sprite = sprite;
    self.relativeAngle = angle;
    self.position = spritePosition;

    [self addChild:sprite];
    return self;

}

@end

@interface StateViewScene : CCScene {

}
@end

@implementation StateViewScene 

-(id) init {
    self = [super init];

    if (!self) {
        return nil;
    }

    StateComponent * body = [[StateComponent alloc] initWithGestureStatewithSprite [CCSprite spriteWithImageNamed:@"body.png"] andPosition: CGPointMake(512,384) RelativeAngle:0];

    [self addChild:body];
    return self;

}
2

There are 2 best solutions below

0
Oleg Hein On

Have you tried to set the content Size of the Node to the Sprite content Size?

-(instancetype) initWithGestureStatewithSprite:(CCSprite*) sprite andPosition: (CGPoint) spritePosition RelativeAngle:(float) angle { 
...
self.contentSize = sprite.contentSize;
...
0
UnhappyStudent On

I managed to solve the problem by converting to node space the StateComponent position couple of times as I actually have a tree like structure of StateComponents with sprites.

Thanks for the help! :)

---Edit---

This article helped me and might be interesting: http://www.koboldtouch.com/display/IDCAR/Converting+Between+Coordinate+Spaces