TheM00s3
TheM00s3

Reputation: 3711

COCOS2d Creating movement when button is held

I am working on making an iPhone game involving a spaceship moving from left to right on the screen. I want to make it such that the ship only moves if the buttons are pressed. Here is my current code that creates movement, but it doesnt stop when the button is no longer pressed.

-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    CGSize winSize = [CCDirector sharedDirector].winSize;

NSSet *allTouches = [event allTouches];
UITouch *touch = [allTouches anyObject];
CGPoint location = [touch locationInView:[touch view]];
location = [[CCDirector sharedDirector] convertToGL:location];

if (CGRectContainsPoint([_paddle2 boundingBox], location)){
     int bottomOfScreenX = 0 + _Paddle1.contentSize.width/2;
   id action = [CCMoveTo actionWithDuration:5 position:ccp(bottomOfScreenX,winSize.height/3) ];
    [_starShip runAction:action];
    [action setTag:1];

}

}

-(void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event
{
     [_starShip stopActionByTag:1];
}

Upvotes: 0

Views: 244

Answers (2)

Pluvius
Pluvius

Reputation: 171

I believe it has to do with your use of "ccTouchesBegan" along with "ccTouchEnded". Notice "touches" versus "touch". They need to be consistent. ccTouchesBegan handles multiple touch events, while ccTouchBegan is meant for a single touch event. So since it appears you are dealing with a single touch event, you really do not need to use ccTouchesBegan. Switch it to ccTouchBegan and you should be fine.

Upvotes: 1

TheM00s3
TheM00s3

Reputation: 3711

THe problem with this code is that the TouchHasEnded and TouchHasBegan are each using different argument setters. THe Touch began is using an NSSet while the TouchEnded is suing a UITouch. Set the TouchHasEnded as a

-(void)ccTouchEnded:(NSSet *)Touches withEvent:(UIEvent *)event;

or

have the touch began

-(void)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event.

The second method will require a slight tweak to the logic.

Upvotes: 0

Related Questions