1
votes

Hey everyone, I'm new to cocos2d and Objective-C so I apologize if there is a simple solution. I am working on some code for a game I am developing. In this game I have a sprite on screen, and I would like this sprite to move opposite of the touch location.

Example: Picture Example

So far my code looks like this:

-(void) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
//Determine location of the tap/touch
CGPoint touchLocation = [touch locationInView: [touch view]];
touchLocation = [[CCDirector sharedDirector] convertToGL: touchLocation];
touchLocation = [self convertToNodeSpace:touchLocation];

I add my sprite to the scene in the init method like so:

        CGSize screenSize = [[CCDirector sharedDirector] winSize];

    Ball* ball = [Ball ball];
    ball.position = CGPointMake(ball.contentSize.width / 2, screenSize.height / 2);
    [self addChild:ball z:2];

I would like it so that wherever I touch on the screen, the sprite will move 20pixels opposite of that touch location. So if I touch to the left of the sprite, the sprite moves right, if I touch to the top, the sprite will move down..etc.

Thanks for the help!

1

1 Answers

1
votes

Use actions. In your touch began method create an action:

CGPoint vector;
vector.x = ball.position.x - touchLocation.x;
vector.y = ball.position.y - touchLocation.y;

float vectorLength = sqrt(vector.x*vector.x + vector.y*vector.y);
if (fabs(vectorLength) < 0.1) return; //tapped directly to the center of sprite

vector.x *= 20 / vectorLength;
vector.y *= 20 / vectorLength;

id action = [CCMoveBy actionWithDuration: 0.5 position: vector];
[ball runAction: action];