Ramy Al Zuhouri
Ramy Al Zuhouri

Reputation: 21966

Cocos2D CCSprite object moving too much

I have subclassed CCSprite to make a Zombie object.It just loads a zombie image and let the user move it:

@implementation Zombie

@synthesize speed; // CGFloat


- (id) initWithPosition: (CGPoint) position
{
    if(self= [super initWithFile: @"zombie_icon.png"])
    {
        CCTouchDispatcher* dispatcher=[CCTouchDispatcher sharedDispatcher];
        self.position=position;
        self.scale= 0.25;
        speed= 50.0;
        [dispatcher addTargetedDelegate: self priority: 0 swallowsTouches: YES];
    }
    return self;
}

#pragma - mark Movements

- (NSTimeInterval) timeFromDestination: (CGPoint) destination
{
    CGFloat distance= sqrt( pow (fabs(self.position.x-destination.x),2) + pow (fabs(self.position.y-destination.y),2));
    return distance/speed;
}

- (BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
    return YES;
}

- (void) ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event
{
    CGPoint location=[self convertTouchToNodeSpace: touch];
    NSTimeInterval duration= [self timeFromDestination: location];
    [self runAction: [CCMoveTo actionWithDuration: duration position: location]];
}



@end

So in my layer I do this:

Zombie* zombie=[[Zombie alloc]initWithPosition: CGPointMake(200, 250)];
[self addChild: zombie];
[zombie release];

The zombie moves sometimes correctly and sometimes not.
For example the zombie is in (100,100), I click in (200,200), it moves towards that direction, but when it reaches (200,200) it keep going until it goes off the screen.
Later I could upload a video if you say that the description of the problem isn't so clear.

Upvotes: 0

Views: 188

Answers (1)

YvesLeBorg
YvesLeBorg

Reputation: 9079

you probably got your destination wrong (logging helps). Your zombie's current position is in parent's node space coordinates, and you have it moving to a destination that in in zombie's node space notation.

Upvotes: 1

Related Questions