Touches in Cocos2d, some bug - ios

I've written the following program, which has to do the following: when user touch moving sprite it has to be removed from the scene.
But, when I run my code the following thing happens: when I touch the uppest sprite it dissappears whith it neighbour. How can I fix it?
Here is the code.
UPD: I've tested this code on smaller *.png file, and everything works fine. But on bigger *.png file (smth like 200x200 pixels, iPhone simulator) I have a bug: object removes on touchEvent with its the nearest neighbour.
definition
#import <Foundation/Foundation.h>
#import "cocos2d.h"
#interface GameplayLayer : CCLayer {
NSMutableArray *arrayOfSprites;
}
#end
#import "GameplayLayer.h"
#implementation GameplayLayer
-(id)init
{
self = [super init];
self.isTouchEnabled=YES;
arrayOfSprites=[[NSMutableArray alloc] init];
if (self != nil)
{
int j=100;
for (int i=0; i<=2; i++) {
[arrayOfSprites addObject:[CCSprite spriteWithFile:#"sv_anim_1-hd.png"]];
[[arrayOfSprites objectAtIndex:i] setPosition:CGPointMake(j,j)];
[self addChild:[arrayOfSprites objectAtIndex:i] z:0 tag:i];
j+=100;
}
[self startRunning];
}
return self;
}
-(void)startRunning
{
CGSize screenSize=[[CCDirector sharedDirector] winSize];
for ( CCSprite * currentSprite in arrayOfSprites)
{
[currentSprite runAction:[CCMoveTo actionWithDuration:10 position:CGPointMake(screenSize.height,screenSize.width/2)]];
}
}
-(void) registerWithTouchDispatcher
{
[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0
swallowsTouches:YES];
}
-(BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
return YES;
}
-(void) ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event {
CGPoint locationOfTouch=[self convertTouchToNodeSpace: touch];
for (CCSprite *currentSprite in arrayOfSprites)
{
if (CGRectContainsPoint(currentSprite.boundingBox, locationOfTouch))
{
NSLog(#"Sprite was touched");
[self removeChild:currentSprite cleanup:YES];
}
}
}
#end

Try this function:
-(CGRect)getSpriteRect:(CCNode *)inSprite
{
CGRect sprRect = CGRectMake(
inSprite.position.x - inSprite.contentSize.width*inSprite.anchorPoint.x,
inSprite.position.y - inSprite.contentSize.height*inSprite.anchorPoint.y,
inSprite.contentSize.width,
inSprite.contentSize.height
);
return sprRect;
}
- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *myTouch = [touches anyObject];
CGPoint location = [myTouch locationInView:[myTouch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
for (CCSprite *currentSprite in arrayOfSprites)
{
CGRect rect = [self getSpriteRect:currentSprite];
if (CGRectContainsPoint(rect, location))
{
NSLog(#"Sprite was touched");
[self removeChild:currentSprite cleanup:YES];
}
}
}

Related

Drag and Drop the Physics Body in cocos2d 3.1?

I am newcomer to cocos2d v3.1
How to drag and drop the Physics body in cocos2d v3.1.
and then how to check the Collision & Detection between two Physics Body's.
Thank you in advance
First, you need a class named CCTouchJoint.
CCTouchJoint.h
#import "Box2D.h"
#interface CCTouchJoint : NSObject
{
#public
b2MouseJoint *mouseJoint;
UITouch *touch;
}
#property (assign) b2MouseJoint *mouseJoint;
#property (nonatomic, retain) UITouch *touch;
- (id)initLocal:(UITouch *)touch withMouseJoint:(b2MouseJoint *)mouseJoint;
+ (id)touch:(UITouch *)touch withMouseJoint:(b2MouseJoint *)mouseJoint;
// Public methods
/**
* Destroy the touch joint in the Box2d world.
*/
- (void)destroyTouchJoint;
#end
CCTouchJoint.mm
#import "CCTouchJoint.h"
#implementation CCTouchJoint
#synthesize mouseJoint;
#synthesize touch;
- (void)dealloc
{
[touch release];
[super dealloc];
}
- (id)initLocal:(UITouch *)_touch withMouseJoint:(b2MouseJoint *)_mouseJoint
{
if ((self = [super init]))
{
self.touch = _touch;
mouseJoint = _mouseJoint;
}
return self;
}
+ (id)touch:(UITouch *)_touch withMouseJoint:(b2MouseJoint *)_mouseJoint
{
return [[self alloc] initLocal:_touch withMouseJoint:_mouseJoint];
}
#pragma mark -
#pragma mark CCTouchJoint Public Methods
- (void)destroyTouchJoint
{
if (mouseJoint != NULL)
{
mouseJoint->GetBodyA()->GetWorld()->DestroyJoint(mouseJoint);
}
}
#pragma mark CCTouchJoint Private Methods
#end
Second. self.touchEnabled = YES; You need
NSMutableArray *touchJointList;
b2Body *groundBody and b2Body *b;
and this touch code:
- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSSet *allTouches = [event allTouches];
for(UITouch *touch in allTouches)
{
CGPoint location = [touch locationInView:touch.view];
location = [[CCDirector sharedDirector] convertToGL:location];
b2Vec2 worldLoc = b2Vec2(ptm(location.x), ptm(location.y));
for (b = world->GetBodyList(); b; b = b->GetNext())
{
if (b->GetType() == b2_dynamicBody)
for (b2Fixture *f = b->GetFixtureList(); f; f = f->GetNext())
{
// Hit!
if (f->TestPoint(worldLoc))
{
/// Mouse joint definition
b2MouseJointDef md;
md.bodyA = groundBody;
md.bodyB = b;
md.target = worldLoc;
md.maxForce = 3000.0 * b->GetMass();
md.dampingRatio = 5;
md.frequencyHz = 60;
// Joint of bodys
b2MouseJoint *m_touchJoint;
m_touchJoint = (b2MouseJoint *)world->CreateJoint(&md);
CCTouchJoint *tj = [CCTouchJoint touch:touch withMouseJoint:m_touchJoint];
[touchJointList addObject:tj];
b->SetAwake(true);
}
break;
}
}
}
}
- (void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
for (CCTouchJoint *tj in touchJointList)
{
if([tj.touch phase] == UITouchPhaseMoved)
{
// Update if it is moved
CGPoint location = [tj.touch locationInView:tj.touch.view];
location = [[CCDirector sharedDirector] convertToGL:location];
b2Vec2 worldLocation = b2Vec2(ptm(location.x), ptm(location.y));
tj.mouseJoint->SetTarget(worldLocation);
}
}
}
- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
NSSet *allTouches = [event allTouches];
NSMutableArray *discardedItems = [NSMutableArray array];
for(UITouch *touch in allTouches)
{
for (CCTouchJoint *tj in touchJointList)
{
if (tj.touch == touch)
{
// Defensive programming - assertion
NSAssert([tj isKindOfClass:[CCTouchJoint class]], #"node is not a touchJoint!");
// If safe - loop through
if ([tj.touch phase] == UITouchPhaseEnded)
{
[discardedItems addObject:tj];
[tj destroyTouchJoint];
[tj release];
}
}
}
}
[touchJointList removeObjectsInArray:discardedItems];
}
- (void)ccTouchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
[touchJointList removeAllObjects];
}
REMEMBER:Changing md.dampingRatio and md.frequencyHz will affect on behavior of mouse joint.
Try the Below link for collision detection. It will be helpful for you.
http://www.cocos2d-x.org/wiki/Chapter_5_-_How_to_Detect_the_Collisions

Move 2 CCSprite with UITouch

I try make a simple game in cocos2d at now i have something like that
#import "GameplayLayer.h"
#implementation GameplayLayer
-(id)init {
self = [super init];
if (self != nil) {
CGSize screenSize = [CCDirector sharedDirector].winSize;
// właczenie obsługi dotyku
self.isTouchEnabled = YES;
if (UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPad) {
}
else{
paddle1 = [CCSprite spriteWithFile:#"bijakiPhone.png"];
paddle2 = [CCSprite spriteWithFile:#"bijakiPhone.png"];
puck = [CCSprite spriteWithFile:#"krazekiPhone.png"];
}
//Polozenie i inicjalizacja paletki nr 1
[paddle1 setPosition:
CGPointMake(screenSize.width/2,
screenSize.height*0.17f)];
[self addChild:paddle1];
//Polozenie i inicjalizacja paletki nr 2
[paddle2 setPosition:
CGPointMake(screenSize.width/2,
screenSize.height*0.83f)];
[self addChild:paddle2];
//Polozenie i inicjalizacja krązka
[puck setPosition:CGPointMake(screenSize.width/2, screenSize.height/2)];
[self addChild:puck];
}
return self;
}
//onEnter
- (void)onEnter
{
[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];
[super onEnter];
}
//onExit
- (void)onExit
{
[[CCTouchDispatcher sharedDispatcher] removeDelegate:self];
[super onExit];
}
-(BOOL)containsTouch:(UITouch *)touch {
CGRect r=[paddle1 textureRect];
CGPoint p=[paddle1 convertTouchToNodeSpace:touch];
return CGRectContainsPoint(r, p );
}
-(BOOL)containsTouch2:(UITouch *)touch {
CGRect r=[paddle2 textureRect];
CGPoint p=[paddle2 convertTouchToNodeSpace:touch];
return CGRectContainsPoint(r, p );
}
-(BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
if ([self containsTouch:touch]){
CCLOG(#"krarzek 1 tapniety");
isTouched1 = YES;
}
if ([self containsTouch2:touch]){
CCLOG(#"krarzek 2 tapniety");
isTouched2 = YES;
}
return YES;
}
-(void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event{
if (isTouched1){
CGPoint newTouchLocation = [touch locationInView:touch.view];
newTouchLocation = [[CCDirector sharedDirector] convertToGL:newTouchLocation];
[paddle1 setPosition:newTouchLocation];
}
if (isTouched2){
CGPoint newTouchLocation = [touch locationInView:touch.view];
newTouchLocation = [[CCDirector sharedDirector] convertToGL:newTouchLocation];
[paddle2 setPosition:newTouchLocation];
}
}
-(void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event{
if (isTouched1){
isTouched1=NO;
CCLOG(#"krarzek 1 zwolniony");
}
if (isTouched2){
isTouched2=NO;
CCLOG(#"krarzek 2 zwolniony");
}
}
#end
Works CCSprite move, but when i touch 2 CCSprite at same time, They overlap itself!
How i can move them separately?
Sorry for my English and Thanks for help!
The reason of your problem that you don't store somewhere what touch is connected to your paddle. So in case of both touches are inside your paddle sprites, both isTouched1 and isTouched2 variables have value YES. So in your ccTouchMoved:withEvent: method both sprites will be placed to the same position in this case. Store your touches in some variable or I suggest to use dictionary for this with touch as a key and sprite that you need to move as value. In this case your ccTouchMoved:withEvent: method will be look like this
-(void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event
{
CGPoint newTouchLocation = [touch locationInView:touch.view];
newTouchLocation = [[CCDirector sharedDirector] convertToGL:newTouchLocation];
CCNode paddle = [_yourDict objectForKey: touch];
[paddle setPosition:newTouchLocation];
}
And names of your methods that determine if sprite contains given touch are not good enough. I could not say what they do without looking through the code.

Moving sprites in cocos2d

I have 6 sprites that I want to move around:
-(id) init
{
if( (self=[super init]) )
{
CGSize winSize = [[CCDirector sharedDirector] winSize];
CCSprite * backGround = [CCSprite spriteWithFile:#"background_ipad.png"];
backGround.position = ccp(winSize.width/2, winSize.height/2);
[self addChild:backGround z:0];
cloth1 = [CCSprite spriteWithFile:#"clothe_1.png"];
cloth1.position = ccp(-200, -15);
[self addChild:cloth1 z:1];
cloth2 = [CCSprite spriteWithFile:#"clothe_2.png"];
cloth2.position = ccp(130, 225);
[self addChild:cloth2 z:2];
cloth3 = [CCSprite spriteWithFile:#"clothe_3.png"];
cloth3.position = ccp(365, 225);
[self addChild:cloth3 z:3];
cloth4 = [CCSprite spriteWithFile:#"clothe_4.png"];
cloth4.position = ccp(-110, -15);
[self addChild:cloth4 z:4];
cloth5 = [CCSprite spriteWithFile:#"clothe_5.png"];
cloth5.position = ccp(130, -20);
[self addChild:cloth5 z:5];
cloth6 = [CCSprite spriteWithFile:#"clothe_6.png"];
cloth6.position = ccp(365, -15);
[self addChild:cloth6 z:6];
}
return self;
[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];
}
and this method to move:
-(void) ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event
{
CGPoint location = [touch locationInView: [touch view]];
location = [[CCDirector sharedDirector] convertToGL: location];
//Sprite follows the finger movement.
[cloth1 setPosition:location];
}
and the thing is that, I want to add more sprites there to move the sprite. I triend adding more sprites in the //follow the finger movement but then all sprites follow the finger movement. I want to move one single sprite. For example: when touching cloth1, move cloth 1; when touching cloth2, move cloth 2; but not both at the same time.
Can someone tell me how to do this?
#interface YourClass : NSObject
{
NSMutableArray *mSpriteArray;
CCSprite *mSpriteOnHand;
}
//In implementation:
-(id) init
{
.. //your old code
..
[mSpriteArray addObject: cloth1];
[mSpriteArray addObject: cloth2];
[mSpriteArray addObject: cloth3];
[mSpriteArray addObject: cloth4];
[mSpriteArray addObject: cloth5];
[mSpriteArray addObject: cloth6];
}
-(void)onEnter
{
[super onEnter];
self.touchEnabled = YES; // self.isTouchEnabled = YES;
}
- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *myTouch = [touches anyObject];
CGPoint location = [myTouch locationInView:[myTouch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
mSpriteOnHand = nil;
for(CCSprite *cloth in mSpriteArray)
{
if(CGRectContainsPoint([cloth boundingBox], location))
{
mSpriteOnHand = cloth;
break;
}
}
}
- (void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView: [touch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
if(mSpriteOnHand)
mSpriteOnHand.position = location;
}
- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
mSpriteOnHand = nil;
}
-(void)onExit
{
[mSpriteArray release];
mSpriteArray = nil;
[super onExit];
}
return statement always terminates function and returns control to the calling function. You wrote:
return self;
[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];
[[CCTouchDispatcher sharedDispatcher]... line will never get executed.
Is your class a subclass of CCLayer? If you set layer's isTouchEnabled property to YES, it will add this layer as standard (non-targeted) touch delegate.
If you must use targeted touch in your layer, you should return YES in -(BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event if you are claiming this touch, and NO if you aren't. Updates of a claimed touch are sent only to the delegate which claimed it.
To determine which sprite is touched: make an instance variable to store "selected" sprite, in touchBegan method check which sprite's bounding box contains touch location and store this sprite in instance variable (also, looks like you want to claim a touch only if it's touching a sprite).
[cloth1 setPosition:location];
-- your sprite will "jump" to touch position. Usually it doesn't look nice. I would get touch's locationInView: and previousLocationInView:, convert them to GL, get the difference and change sprite's position by that difference.

Cocos2d Drawing App Making Lines

I am making a very simple drawing application. I got the lines to draw using the ccTouchMoved event. I am putting all the touch moved moved points into an array and then using a for loop to draw a line between all the points. Now, I do not want to join the points when I have lifted my finger and started new line drawing. I got that part working too but now whenever I begin a new drawing the whole screen flicker.
//
// HelloWorldLayer.mm
// DrawPuppets
//
// Created by Mohammad Azam on 12/11/12.
// Copyright __MyCompanyName__ 2012. All rights reserved.
//
// Import the interfaces
#import "DrawPuppetLayer.h"
#import "AppDelegate.h"
#import "PhysicsSprite.h"
enum {
kTagParentNode = 1,
};
#pragma mark - HelloWorldLayer
#interface DrawPuppetLayer()
-(void) initPhysics;
-(void) addNewSpriteAtPosition:(CGPoint)p;
-(void) createMenu;
#end
#implementation DrawPuppetLayer
+(CCScene *) scene
{
// 'scene' is an autorelease object.
CCScene *scene = [CCScene node];
// 'layer' is an autorelease object.
DrawPuppetLayer *layer = [DrawPuppetLayer node];
// add layer as a child to scene
[scene addChild: layer];
// return the scene
return scene;
}
-(id) init
{
if( (self=[super init])) {
// enable events
self.isTouchEnabled = YES;
self.isAccelerometerEnabled = YES;
index = -1;
canvas = [[NSMutableArray alloc] init];
// init physics
[self initPhysics];
[self scheduleUpdate];
}
return self;
}
-(void) draw
{
if([lineDrawing.points count] > 1)
{
for(int i = 0; i<([canvas count]) ;i++)
{
LineDrawing *drawing = (LineDrawing *) [canvas objectAtIndex:i];
for(int j=0;j<[drawing.points count] - 1;j++)
{
LinePoint *firstPoint = (LinePoint *) drawing.points[j];
LinePoint *secondPoint = (LinePoint *) drawing.points[j + 1];
CGPoint point1 = [[CCDirector sharedDirector] convertToGL:CGPointMake(firstPoint.x, firstPoint.y)];
CGPoint point2 = [[CCDirector sharedDirector] convertToGL:CGPointMake(secondPoint.x, secondPoint.y)];
ccDrawLine(point1, point2);
}
}
}
//
// IMPORTANT:
// This is only for debug purposes
// It is recommend to disable it
//
[super draw];
ccGLEnableVertexAttribs( kCCVertexAttribFlag_Position );
kmGLPushMatrix();
world->DrawDebugData();
kmGLPopMatrix();
}
-(void) ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
lineDrawing = [[LineDrawing alloc] init];
lineDrawing.points = [[NSMutableArray alloc] init];
[canvas addObject:lineDrawing];
}
-(void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint point = [touch locationInView: [touch view]];
LinePoint *linePoint = [[LinePoint alloc] init];
linePoint.x = point.x;
linePoint.y = point.y;
[lineDrawing.points addObject:linePoint];
}
- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
//Add a new body/atlas sprite at the touched location
for( UITouch *touch in touches ) {
CGPoint location = [touch locationInView: [touch view]];
location = [[CCDirector sharedDirector] convertToGL: location];
}
}
#end
Can anyone spot my mistake?
Try visiting it all down to a texture, there's going to be a time when your points array gets too large to be drawn nicely
-(void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
// get the node space location of our touch
CGPoint location = [self getNodeSpaceTouchLocationFromUIEvent:event];
// draw with our current location and a random colour
[_canvas begin]; // our rendertexture instance
// do your drawing here
[_pen drawPenWithPosition:location andColour:_colour];
// end capturing the current pen state
[_canvas end];
}
Here's a simple example project written for iOSDevUK 2012 it uses GL_POINTS in Cocos2d v1 and is based on the approach we took when developing SketchShare

CGRect and touch

In this cocos2d app the nslog is not firing when I press the ccsprite. Could someone help me?
-(BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event{
NSMutableArray *targetsToDelete = [[NSMutableArray alloc] init];
for (CCSprite *target in _targets) {
CGRect targetRect = CGRectMake(target.position.x - (target.contentSize.width/2),
target.position.y - (target.contentSize.height/2),
27,
40);
CGPoint touchLocation = [self convertTouchToNodeSpace:touch];
if (CGRectContainsPoint(targetRect, touchLocation)) {
NSLog(#"Moo cheese!");
}
}
return YES;
}
First of all be sure that you register the sprite for touches into the onEnter method for example:
- (void)onEnter
{
[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:defaultTouchPriority_ swallowsTouches:YES];
[super onEnter];
}
This will make your sprite touchable and so fire the event to the sprite when a user will press it.
Then refactor your code to make it more readable and test something like that:
- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
CGPoint touchLocation = [self convertTouchToNodeSpace:touch];
NSArray *targetsToDelete = [self touchedSpritesAtLocation:touchLocation];
// Put your code here
// ...
return YES;
}
- (NSArray *)touchedSpritesAtLocation:(CGPoint)location
{
NSMutableArray *touchedSprites = [[NSMutableArray alloc] init];
for (CCSprite *target in _targets)
if (CGRectContainsPoint(target.boundingBox, location))
[touchedSprites addObject:target];
return [touchedSprites autorelease];
}
It should return the targets that have been touched.
In layer init method add this
self.isTouchEnabled = true;
Use this code for touch detection
- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *myTouch = [touches anyObject];
CGPoint location = [myTouch locationInView:[myTouch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
CGRect rect = [self getSpriteRect:yourSprite];
if (CGRectContainsPoint(rect, location))
{
NSLog(#"Sprite touched\n");
}
}
To get sprite rect:
-(CGRect)getSpriteRect:(CCNode *)inSprite
{
CGRect sprRect = CGRectMake(
inSprite.position.x - inSprite.contentSize.width*inSprite.anchorPoint.x,
inSprite.position.y - inSprite.contentSize.height*inSprite.anchorPoint.y,
inSprite.contentSize.width,
inSprite.contentSize.height
);
return sprRect;
}

Resources