How to detect touch outside (empty space) - cocos2d - cocos2d-iphone

This is my code for detect that if touch on a specific sprite
- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *myTouch = [touches anyObject];
CGPoint location = [myTouch locationInView:[myTouch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
for(CCSprite *sprite in shapeArray)
{
if(CGRectContainsPoint(sprite.boundingBox, location))
{
//There is a sprite that is touched
mSpriteOnHand = sprite;
currentPoint = mSpriteOnHand.position;
break;
}
//This part didn't work
else
{
NSLog(#"Touch outside);
}
}
}
Now I want to detect if touch is outside(not on any sprite or empty space) but I don't know how to do it.

If your touches are working, than I think adding a BOOL and then an if statement outside the for loop, like this will work.
BOOL itemFound = NO;
for(CCSprite *sprite in shapeArray)
{
if(CGRectContainsPoint(sprite.boundingBox, location))
{
//There is a sprite that is touched
mSpriteOnHand = sprite;
currentPoint = mSpriteOnHand.position;
NSLog(#"item TOUCHED");
itemFound = YES;
break;
}
}
if (itemFound == NO)
{
NSLog(#"Touch outside");
}

Related

can't remove target from the self in cocos2d-iphone

I use following code to create some sprites
-(void)dologic
{
for (int i = 0; i < 3; i ++) {
CCSprite *target = [CCSprite spriteWithFile:#"pig.png"];
int x = arc4random() % 320;
int y = arc4random() % 300;
target.position = ccp(x, y);
[self addChild:target];
[_targets addObject:target];//_targets is nsmutablearray
}
}
- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint location = [self convertTouchToNodeSpace: touch];
for (CCSprite *target in _targets) {
if (CGRectContainsPoint(target.boundingBox, location)) {
[_targets removeAllObjects];
[self removeChild:target cleanup:YES];
[self dologic];
}
}
when touch any sprite, all sprites will be removed from the self first, and then call dologic to create three new sprites again, but my code can only remove the target that i touched, how can i remove all sprites when i touch the screen?
First off, you are modifying the array while iterating it, which is not a good practice.
If you want to remove all targets upon touching any of them, you can try this:
- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint location = [self convertTouchToNodeSpace: touch];
BOOL touchedASprite = NO;
for (int i = 0; i < [_targets count] && !touchedASprite; ++i) {
if (CGRectContainsPoint((CCSprite*)[_targets objectAtIndex:i].boundingBox, location)) {
touchedASprite = YES;
}
}
if (touchedASprite) {
for (CCSprite *target in _targets) {
[self removeChild:target cleanup:YES];
}
[_targets removeAllObjects];
[self doLogic];
}
}
When you want to remove objects in a array while browsing all objects of it, you should do like this:
for (int i = (int)_targets.count - 1 ; i >= 0 ; i--) {
CCSprite *target = _targets[i];
if (CGRectContainsPoint(target.boundingBox, location)) {
[_targets removeAllObjects];
[self removeChild:target cleanup:YES];
[self dologic];
}
}
Be careful: [NSArray count] returns a unsigned number, when [NSArray count] returns 0, ([NSArray count]-1) is NOT -1, should cast it to int

Drag a sprite attached to a body

I have a CCSprite that is attached to body in a b2world .
When someone is touch it, i want to move it with the touch location.
With a regular sprite that works fine , but with a sprite that has a body- it does not .
it gets the touch but not move the sprite (the body follow the sprite or the opposite?)
How should i do that ? apply a force relative to the touch is a problem..
- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint currentPosition = [touch locationInView: [touch view]];
//detect a touch ont the button
for (b2Body* b = world->GetBodyList(); b; b = b->GetNext())
{
CGPoint location=[[CCDirector sharedDirector] convertToGL: currentPosition];
CCSprite *tempSprite = (CCSprite *) b->GetUserData();
if( tempSprite.tag==2 )
{
if(CGRectContainsPoint([tempSprite boundingBox], location))
{
tempSprite.position=location;
NSLog(#"touched");
}
}
}
}
Try changing the position of the body using SetTransform function. I think it's looking something like:
- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint currentPosition = [touch locationInView: [touch view]];
//detect a touch ont the button
for (b2Body* b = world->GetBodyList(); b; b = b->GetNext())
{
CGPoint location=[[CCDirector sharedDirector] convertToGL: currentPosition];
CCSprite *tempSprite = (CCSprite *) b->GetUserData();
if( tempSprite.tag==2 )
{
if(CGRectContainsPoint([tempSprite boundingBox], location))
{
b->SetTransform( b2Vec2( location.x/PTM_RATIO, location.y/PTM_RATIO ), 0 ); //change position of the body
NSLog(#"touched");
}
}
}
}
Don't forget, if you want to change body position apply force or set linear velocity you must use kinematic or dynamic body type.

MultiTouch control of a sprites movement - cocos2d

I've been dealing with this problem for quite some time.
What I am trying to do is have a CCSprite's right/left movement controlled by touches on either the left side of the screen or the right.
Doing this is no problem if you lift your finger after each touch. But what I want is best described by an example:
The player touches the left side of the screen and the sprite moves to the left. Now the player (while still touching the left side) touches the right side...the sprite should now move right. Now the player has one finger on the left and one on the right side, if he now lifts the touch off the right side the sprite should again move to the left.
This is what I have now:
-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
NSSet *allTouches = [event allTouches];
UITouch * touch = [[allTouches allObjects] objectAtIndex:0];
CGPoint location = [touch locationInView: [touch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
if (location.x < 240) {
[player walk:kkMoveLeft];
} else if (location.x > 240) {
[player walk:kkMoveRight];
}
//Swipe Detection Part 1
firstTouch = location;
}
-(void) ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
NSSet *allTouches = [event allTouches];
UITouch * touch = [[allTouches allObjects] objectAtIndex:0];
CGPoint location = [touch locationInView: [touch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
//Swipe Detection Part 2
lastTouch = location;
float swipeLength = ccpDistance(firstTouch, lastTouch);
if (firstTouch.y < lastTouch.y && swipeLength > 60) {
[player jump:kkJumpUp];
} else if (firstTouch.y > lastTouch.y && swipeLength > 60){
[player jump:kkJumpDown];
}
[player endWalk];
}
I'd appreciate it if someone could tell me how to go about this. Thank you .
UPDATE MY SOLUTION:
//1. Enable multitouch in the appDelegate
[glView setMultipleTouchEnabled:YES];
//2. Create an Array to keep track of active touches
touchArray = [[NSMutableArray alloc] init];
//3. Touch Methods
-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
for (UITouch *touch in touches) {
if (![touchArray containsObject:touch]) {
[touchArray addObject:touch];
CGPoint location = [touch locationInView:[touch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
CCLOG(#"start: %f", location.x);
if (location.x < 240) {
[player walk:kkMoveLeft];
} else if (location.x > 240) {
[player walk:kkMoveRight];
}
}
}
}
-(void) ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
for (UITouch *touch in touches) {
[touchArray removeObject:touch];
CGPoint location = [touch locationInView:[touch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
CCLOG(#"end: %f", location.x);
}
for (UITouch *touch in touchArray) {
CGPoint location = [touch locationInView:[touch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
CCLOG(#"still: %f", location.x);
if (location.x < 240) {
[player walk:kkMoveLeft];
} else if (location.x > 240) {
[player walk:kkMoveRight];
}
}
if ([touchArray count] == 0) {
[player endWalk];
}
}
If I understand correctly your problem, what you should do is:
in ccTouchesEnded, instead of simply calling endWalk, check to see is any touch is still present (to do so, you could iterate over allTouches);
in the appropriate case (i.e., a touch is still activating the player), call startWalk.
if no touch is present, call endWalk.
The code would be similar to what you have in ccTouchesBegan, only you iterate (I am not sure what allTouches contains at index 0 in touchesEnded).
OLD ANSWER:
You are not saying anything about how you are handling touches right now. In any case, the way to go is defining ccTouches* methods (vs. ccTouch*), where * can be: Began, Moved, Ended.
-(void)tccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
CGPoint location = [touch locationInView:[touch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
...
}
-(void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
...
}
-(void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
...
}
Keep in mind that touchesBegan is fired at each new touch that is detected. So, if you want to know the status of all touches currently active, you have to use allTouches.
Have also a look at this post from iphonesdk which I found insightful as to the semantics of touches in those methods.

COCOS2D. dragging CCSprite on the screen with ccTouchMoved makes the movement jerky

I have an issue with my ccTouchMoved method. I have 3 ccSprites what I want to be able to move around on the screen using my finger. The thing is that the movement is jerky and it sometimes even looses "the grip" of the ccSprites when dragging the image, if I move the mouse pointer to fast.
what am I missing?
the three touchmethods that I use have the following tasks:
ccTouchBegan : scale up the ccSprite that is being touched
ccTouchMoved : move the ccSprite that is touched across the screen
ccTouchEnded: scale down the ccSprite to it's original size and stop the movement (is there a better way of scaling down the ccSprite to it's original size?)
- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event{
CCLOG(#"ccTouchBeganRuby");
CGPoint location = [self convertTouchToNodeSpace: touch];
if(CGRectContainsPoint([animatingRuby1 boundingBox], location)){
CCLOG(#"ccTouchEndedRubyScaleUp1");
id ScaleAction1 = [CCScaleBy actionWithDuration:1 scale:1.2f ];
[animatingRuby1 runAction:ScaleAction1];
}
if(CGRectContainsPoint([animatingRuby2 boundingBox], location)){
CCLOG(#"ccTouchEndedRubyScaleUp2");
id ScaleAction2 = [CCScaleBy actionWithDuration:1 scale:1.2f ];
[animatingRuby2 runAction:ScaleAction2];
}
if(CGRectContainsPoint([animatingRuby3 boundingBox], location)){
CCLOG(#"ccTouchEndedRubyScaleUp3");
id ScaleAction3 = [CCScaleBy actionWithDuration:1 scale:1.2f ];
[animatingRuby3 runAction:ScaleAction3];
}
return YES;
}
- (void)ccTouchMoved:(UITouch *)touches withEvent:(UIEvent *) event{
CCLOG(#"ccTouchMovedRuby");
if (CGRectContainsPoint([animatingRuby1 boundingBox], location)) {
CCLOG (#"moveRubies1");
if((CGRectContainsPoint([animatingRuby2 boundingBox], location))|| (CGRectContainsPoint([animatingRuby1 boundingBox], location))) {
return;
}
animatingRuby1.position = location;
}
if (CGRectContainsPoint([animatingRuby2 boundingBox], location)) {
CCLOG (#"moveRubies2");
if((CGRectContainsPoint([animatingRuby1 boundingBox], location))|| (CGRectContainsPoint([animatingRuby3 boundingBox], location))) {
return;
}
animatingRuby2.position = location;
}
if (CGRectContainsPoint([animatingRuby3 boundingBox], location)) {
CCLOG (#"moveRubies3");
if((CGRectContainsPoint([animatingRuby1 boundingBox], location))|| (CGRectContainsPoint([animatingRuby2 boundingBox], location))) {
return;
}
animatingRuby3.position = location;
}
[self collidableWithEachOther:location];
}
- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *) event{
CGSize screenSize = [[CCDirector sharedDirector] winSize];
CCLOG(#"ccTouchEndedRuby");
CGPoint location = [self convertTouchToNodeSpace: touch];
if(CGRectContainsPoint([animatingRuby1 boundingBox], location)){
CCLOG(#"ccTouchEndedRubyScaleDown1");
[animatingRuby1 setScaleX:screenSize.width/14850.0f];
[animatingRuby1 setScaleY:screenSize.height/9552.0f];
}
if(CGRectContainsPoint([animatingRuby2 boundingBox], location)){
CCLOG(#"ccTouchEndedRubyScaleDown2");
[animatingRuby2 setScaleX:screenSize.width/14850.0f];
[animatingRuby2 setScaleY:screenSize.height/9552.0f];
}
if(CGRectContainsPoint([animatingRuby3 boundingBox], location)){
CCLOG(#"ccTouchEndedRubyScaleDown3");
[animatingRuby3 setScaleX:screenSize.width/14850.0f];
[animatingRuby3 setScaleY:screenSize.height/9552.0f];
}
}
Take the vector from the sprite to the touch location and set it as the direction for the sprite, while limiting its speed. This way changes won't be as quick and drastic and the movement will look smoother. Don't require that the touch location always be over the sprite, just keep track of whether a drag operation is taking place, and which sprite is being dragged.

serious multitouch problem

I am almost done with my game but I can't get my multi touch working :
I got in my appdelegate
[glView setMultipleTouchEnabled:YES];
(also tried [window setMultiTouchEnabled:YES];)
In my Bomb.h
#interface Bomb : CCLayer (I also tried CCNode with <ccTargetTouchDelegate>)
Bomb.m
-(void)onEnter
{
[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:kCCMenuTouchPriority swallowsTouches:YES];
[super onEnter];
}
-(void)onExit
{
[[CCTouchDispatcher sharedDispatcher] removeDelegate:self];
[super onExit];
}
(Also tried registerWithTouchDispatcher withouth onEnter and onExit and also tried with [super registerWithTouchDispatcher])
-(BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
if(isPaused || !canBeDragged || LOST)
return NO;
//take the coordinates of the touch and transform them into the OpenGL system.
CGPoint location = [touch locationInView: [touch view]];
location = [[CCDirector sharedDirector] convertToGL: location];
CGRect frame = CGRectMake(self.position.x, self.position.y, self.contentSize.width, self.contentSize.height);
if(!CGRectContainsPoint(frame, location))
return NO;
location.x *= factor;
location.y *= factor;
if(BombShape)
{
offsetX = BombShape->body->p.x – location.x;
offsetY = BombShape->body->p.y – location.y;
BombShape->body->v = cpvzero;
BombShape->collision_type++; //make it ‘Dragged’. For example RedNinja++ is DraggedRedNinja
}
return YES;
}
//****************************************************************************************
- (void) ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event
{
if(isPaused || !canBeDragged)
return;
CGPoint location = [touch locationInView: [touch view]];
location = [[CCDirector sharedDirector] convertToGL: location];
CGPoint prevLocation = [touch previousLocationInView: [touch view]];
prevLocation = [[CCDirector sharedDirector] convertToGL: prevLocation];
location.x *= factor;
location.y *= factor;
prevLocation.x *= factor;
prevLocation.y *= factor;
if(BombBody)
{
//during the dragging, the bomb must not have velocity. Otherwise, it will “run” beneath your finger.
//so we are constantly calculating the velocity and ,when you end the draging, assign that value to the velocity of the bomb.
velocity = cpv((location.x – prevLocation.x) * 30 , (location.y – prevLocation.y)*30);
CGPoint newPosition = cpv(location.x + offsetX, location.y + offsetY);
//test per X
canMoveOnX = CheckOnX(BombBody->p , newPosition,radius);
canMoveOnY = CheckOnY(BombBody->p , newPosition,radius);
if(canMoveOnX)
BombBody->p.x = newPosition.x;
if(canMoveOnY)
BombBody->p.y = newPosition.y;
}
}
//****************************************************************************************
- (void) ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event
{
if(!canBeDragged || isPaused)
return;
//set velocity back
BombShape->body->v = velocity;
BombShape->collision_type–;
offsetX = 0;
offsetY = 0;
}
//****************************************************************************************
-(void) ccTouchCancelled:(UITouch *)touch withEvent:(UIEvent *)event
{
}
Somehow I can't seem to detect my second touch :S.
I am loading my Bomb.h in a GameScene that is a CCLayer without touches.
Please help. Thanks.
I had the same problem.
If you have another view, like a view for ad, you should do the same thing to that.
ex.
[yourAnotherView setMultipleTouchEnabled:YES];
If you don't, sorry I cannot answer any more...