Henley Bailey
Henley Bailey

Reputation: 11

Cocos2d, moving a sprite to a touch location

myself and my friend have been told Stackoverflow is the place to ask questions regarding code. :)

We're pretty new to Objective-C, Xcode and Cocos2d and are trying to complete simple tasks to further our knowledge.

Looking at our code below, we have made an Ant Object and placed him on screen. We now want to use a touch location to move the ant to to location the user touches.

We're unsure what the correct way to go about it is. At the moment we're staying away from creating classes so have all the code in one place but we can't figure out how to get the ant that's on screen to go to the touch location.

Can anyone help?

    //
//  HelloWorldLayer.m
//  Timer
//
//  Created by Lion User on 06/06/2012.
//  Copyright __MyCompanyName__ 2012. All rights reserved.
//


// Import the interfaces
#import "HelloWorldLayer.h"

// HelloWorldLayer implementation
@implementation HelloWorldLayer

+(CCScene *) scene
{
    // 'scene' is an autorelease object.
    CCScene *scene = [CCScene node];

    // 'layer' is an autorelease object.
    HelloWorldLayer *layer = [HelloWorldLayer node];

    // add layer as a child to scene
    [scene addChild: layer];

    // return the scene
    return scene;
}



// on "init" you need to initialize your instance
-(id) init
{
    if( (self=[super initWithColor:ccc4(225, 225, 225, 255)])) {

        // enable touches
        self.isTouchEnabled=YES;

        // ask director the the window size
        CGSize size = [[CCDirector sharedDirector] winSize];


        // set time to zero
        myTime = currentTime;
        timeLabel = [CCLabelTTF labelWithString:@"00:00" fontName:@"Arial" fontSize:48];
        timeLabel.position = CGPointMake(size.width / 2, size.height);
        // set label color
        timeLabel.color = ccBLACK;
        // Adjust the label's anchorPoint's y position to make it align with the top.
        timeLabel.anchorPoint = CGPointMake(0.5f, 1.0f);
        // Add the time label
        [self addChild:timeLabel];

        // run create ant method
        [self createAnt];

        //update
        [self schedule:@selector(update:)];

    }
    return self;
}

-(void)update:(ccTime)dt{

    totalTime += dt;
    currentTime = (int)totalTime;
    if (myTime < currentTime)
    {
        myTime = currentTime;
        [timeLabel setString:[NSString stringWithFormat:@"%02d:%02d", myTime/60, myTime%60]];
    }

}

////* method for creating an ant and moving it*////
-(void)createAnt{

    ////*requirements for animation setup*////

    // create cache object to store spritesheet in
    CCSpriteFrameCache *cache=[CCSpriteFrameCache sharedSpriteFrameCache];
    // add the sprite list to the cache object
    [cache addSpriteFramesWithFile:@"antatlas.plist"];
    // create frame array to store the frames in
    NSMutableArray *framesArray=[NSMutableArray array];

    //loop through each frame
    for (int i=1; i<3; i++){
        // increment the name to include all frames in sprite sheet
        NSString *frameName=[NSString stringWithFormat:@"ant%d.png", i];
        // create frame object set it to the cache object and add the frameNames to the cache
        id frameObject=[cache spriteFrameByName:frameName];
        // add the frame object into the array
        [framesArray addObject:frameObject];

    }

    ////* setup the actions for running the animation*////

    // create animation object and pass the list of frames to it (it expects this as an array)
    id animObject=[CCAnimation animationWithFrames:framesArray delay:0.05];
    // setup action to run the animation do not return to frame 1
    id animationAction=[CCAnimate actionWithAnimation:animObject restoreOriginalFrame:NO];
    //loop the animation indefinitely
    animationAction = [CCRepeatForever actionWithAction:animationAction];
    // move ant action
    id moveAnt=[CCMoveTo actionWithDuration:3 position:ccp(60, 160)];

    // create sprite, set location and add to layer (starts with the name of the first frame in the animation
    CCSprite *ant=[CCSprite spriteWithSpriteFrameName:@"ant1.png"];
    ant.position=ccp(240, 160);
    [self addChild:ant];


    //run animation action
    [ant runAction: animationAction];
    // run move ant action
    [ant runAction:moveAnt];

}

-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch=[touches anyObject];
    CGPoint loc=[touch locationInView:[touch view]];
    loc=[[CCDirector sharedDirector]convertToGL:loc];
    NSLog(@"touch (%g,%g)",loc.x,loc.y);

    // Move ant to point that was pressed
    [ant runAction:[CCSequence actions:
    [CCMoveTo actionWithDuration:realMoveDuration position:loc],
    [CCCallFuncN actionWithTarget:self selector:@selector(spriteMoveFinished:)],
     nil]];
}


// on "dealloc" you need to release all your retained objects
- (void) dealloc
{

    [super dealloc];
}
@end

Upvotes: 1

Views: 2124

Answers (1)

Justin at CartoonSmart
Justin at CartoonSmart

Reputation: 166

Seems like your ant is local to your createAnt method. So in the touchesBegan statement, it doesn't "see" the ant. Go over to your header file, and in the @interface declare the ant...

CCSprite *ant;

Then back in your createAnt statement, you can just write...

ant=[CCSprite spriteWithSpriteFrameName:@"ant1.png"];

Now any other method in the implementation ( .m ) file will know what you mean when you write "ant"

Hope it helps!

Upvotes: 2

Related Questions