views:

603

answers:

2

In cocos2d does anyone know how to center a sprite? Right now, I have a sprite that moves to where you touch on the screen. The problem is that the sprite is aligned to the lower left corner. This means that instead of moving down, if you touch just a little over the bottom the sprite will move up. Thanks in advance!

Here is my code...

(BOOL) ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *) event {
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView: [touch view]];

    [mainSprite do:[MoveTo actionWithDuration:0.5 position:ccp(point.x, 480 - point.y)]];

    return YES;
}
+1  A: 

The default transformation anchor for sprites in Cocos2D is the center of the sprite, so it should be moving such that the center of the sprite ends up in the touched location as you have it now. Have you changed the sprite's transform anchor?

The only other thing I can think of is that if your mainSprite is a child of another CocosNode then you may need to convert the touch coordinates to node space using this method:

- (CGPoint)convertToNodeSpace:(CGPoint)worldPoint;

...on the parent node. However, I doubt that is the problem. Sorry if this is unhelpful.

EDIT: OP, if you read this, what version of Cocos2D are you using? I believe 0.8 (currently in the svn trunk) changes the way that anchoring works; for future reference it may be useful to others to know what you're working with.

Mitch Lindgren
A: 

I got it working! For anyone that wants to know here is the code...

[mainSprite setTransformAnchor:ccp(24.0, 64.5)];

24 is half of the sprites width

64.5 is half of the sprites height