TheFityP
TheFityP

Reputation: 85

Cocos2d-iPhone Drag anywhere to move sprite

Ok what I would like to do is duplicate the controls of Space Invaders Evolution.

Begin a touch anywhere then drag around and the sprite moves 1:1 with your finger. Sprite can not be moved of screen.

I have been using UIGestureRecognizer to handle dragging the sprite around the screen but im still pretty new to this and I have not been able to get this to work yet.

Upvotes: 1

Views: 764

Answers (2)

ScottPetit
ScottPetit

Reputation: 814

I don't know if you're unwilling to try this but it seems to me that this sort of thing could easily be done using ccTouchesBegan and ccTouchesMoved. I'd implement it by putting the following in my ccTouchesBegan and ccTouchesMoved methods (where sprite is the name of the sprite you're trying to move):

UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView:[touch view]];    
location = [[CCDirector sharedDirector] convertToGL:location];
sprite.position = ccp(location.x, location.y);

Upvotes: 1

nash
nash

Reputation: 2181

Are you using Cocos2D or the Apple Frame-work?

In cocos2d you could use a layer (your scene for example) to detect the touch, which then moves the sprite. When the move is applied, check whether the sprite is still within screen boundaries, and move it back into screen boundaries if it's not.

There is example touch code in the cocos2d distribution. Not for your specific case, but general code, with text and explanation.

Upvotes: 0

Related Questions