I've been trying to draw a sprite line between 2 points made by sprites with mouse events on Xcode.
I have been following the steps given on a forum in this link:
cocos2d forums
But when i run the code, i get the line going all the way of the simulator. just like this.
snapshot1
The line should stop by the second mouse sprite generated code, but it doesn't and keeps going all the way.
My Scene is something like this.
My .h class
#import <Foundation/Foundation.h>
#import "cocos2d.h"
#import "Constants.h"
#import "SceneManager.h"
#interface EscenaInfo : CCLayer{
CGPoint lastTouchPoint;
CCSprite * background;
}
#property (nonatomic, assign) BOOL iPad;
#end
My .mm
#import "EscenaInfo.h"
#implementation EscenaInfo
#synthesize iPad;
- (void)onBack: (id) sender {
/*
This is where you choose where clicking 'back' sends you.
*/
[SceneManager goMenuPrincipal];
}
- (void)addBackButton {
if (self.iPad) {
// Create a menu image button for iPad
CCMenuItemImage *goBack = [CCMenuItemImage itemFromNormalImage:#"Arrow-Normal-iPad.png"
selectedImage:#"Arrow-Selected-iPad.png"
target:self
selector:#selector(onBack:)];
// Add menu image to menu
CCMenu *back = [CCMenu menuWithItems: goBack, nil];
// position menu in the bottom left of the screen (0,0 starts bottom left)
back.position = ccp(64, 64);
// Add menu to this scene
[self addChild: back];
}
else {
// Create a menu image button for iPhone / iPod Touch
CCMenuItemImage *goBack = [CCMenuItemImage itemFromNormalImage:#"Arrow-Normal-iPhone.png"
selectedImage:#"Arrow-Selected-iPhone.png"
target:self
selector:#selector(onBack:)];
// Add menu image to menu
CCMenu *back = [CCMenu menuWithItems: goBack, nil];
// position menu in the bottom left of the screen (0,0 starts bottom left)
back.position = ccp(32, 32);
// Add menu to this scene
[self addChild: back];
}
}
- (id)init {
if( (self=[super init])) {
// Determine Screen Size
CGSize screenSize = [CCDirector sharedDirector].winSize;
//Boton en la Interfaz del iPad
self.iPad = UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad;
// Put a 'back' button in the scene
[self addBackButton];
///
self.isTouchEnabled = YES;
lastTouchPoint = ccp(-1.0f,-1.0f);
///
[CCTexture2D setDefaultAlphaPixelFormat:kCCTexture2DPixelFormat_RGB565];
background = [CCSprite spriteWithFile:#"background.png"];
background.anchorPoint = ccp(0,0);
[self addChild:background z:-1];
[CCTexture2D setDefaultAlphaPixelFormat:kCCTexture2DPixelFormat_Default];
}
return self;
}
- (void) dealloc
{
// in case you have something to dealloc, do it in this method
// in this particular example nothing needs to be released.
// cocos2d will automatically release all the children (Label)
// don't forget to call "super dealloc"
[super dealloc];
}
- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
if( touch ) {
CGPoint location = [touch locationInView: [touch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
CCLOG(#"location(%f,%f)", location.x, location.y);
if( CGPointEqualToPoint(lastTouchPoint, ccp(-1.0f,-1.0f) ) )
{
lastTouchPoint = ccp(location.x, location.y);
CCSprite *circle = [CCSprite spriteWithFile:#"circle.png"];
[circle setPosition:lastTouchPoint];
[self addChild:circle];
CCLOG(#"initial touchpoint set. to (%f,%f)", lastTouchPoint.x, lastTouchPoint.y);
}
else {
CCLOG(#"lastTouchPoint is now(%f,%f), location is (%f,%f)", lastTouchPoint.x, lastTouchPoint.y, location.x, location.y);
CGPoint diff = ccpSub(location, lastTouchPoint);
float rads = atan2f( diff.y, diff.x);
float degs = -CC_RADIANS_TO_DEGREES(rads);
float dist = ccpDistance(lastTouchPoint, location);
CCSprite *line = [CCSprite spriteWithFile:#"line.png"];
[line setAnchorPoint:ccp(0.0f, 0.5f)];
[line setPosition:lastTouchPoint];
[line setScaleX:dist];
[line setRotation: degs];
[self addChild:line];
CCSprite *circle = [CCSprite spriteWithFile:#"circle.png"];
[circle setPosition:location];
[self addChild:circle];
// lastTouchPoint = ccp(location.x, location.y);
lastTouchPoint = ccp(-1.0f,-1.0f);
}
}
}
#end
Does anyone knows how to work this out? i have been trying lots of things but nothing has worked for me, or maybe point out my mistake. i would really appreciate this.
I've not run the code but it looks fairly straightforward. The cause of the problem lies in this section:
float dist = ccpDistance(lastTouchPoint, location);
CCSprite *line = [CCSprite spriteWithFile:#"line.png"];
[line setAnchorPoint:ccp(0.0f, 0.5f)];
[line setPosition:lastTouchPoint];
[line setScaleX:dist];
This code calculates the distance between the two touch points in points (pixels), creates a new sprite (that will become the line) and sets the anchor point to the right hand side, centred vertically. It positions this at the point of the last touch and then sets the scale of the sprite's width based on the distance calculated earlier. This scaling factor will ensure the sprite is 'long' enough to reach between the two points.
Your issue:
This isn't taking into account the initial dimensions of the image you are loading (line.png). If this isn't a 1x1 dimension png then the setScale is going to make the resulting sprite too large - the overrun you are experiencing.
The Solution
Make line.png a 1 x 1 pixel image. Your code will work perfectly, though you will have a very thin line that is not aesthetically pleasing.
Or, for best results, calculate the scale for the sprite by taking into account the width of line.png. This way the sprite can be more detailed and won't overrun.
Change thesetScaleX line to this:
[line setScaleX:dist / line.boundingBox.size.width];
Using Cocos2D v3.x this works:
in -(void)update:(CCTime)delta{} you do this:
[self.drawnode drawSegmentFrom:ccp(50,100) to:ccp(75, 25) radius:3 color:self.colorDraw];
The self.drawnode and self.colorDraw properties are initialized like this, maybe inside -(void)onEnter{} :
self.drawnode = [CCDrawNode node];
self.colorDraw = [CCColor colorWithCcColor3b:ccRED];
[self addChild:self.drawnode];
I think you can use core graphics here :
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context,4);
CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
CGContextMoveToPoint(context,startPoint.x , startPoint.y);
CGContextAddLineToPoint(context, endPoint.x, endPoint.y);
CGContextStrokePath(context);
}
- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
UITouch* touchPoint = [touches anyObject];
startPoint = [touchPoint locationInView:self];
endPoint = [touchPoint locationInView:self];
[self setNeedsDisplay];
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch* touch = [touches anyObject];
endPoint=[touch locationInView:self];
[self setNeedsDisplay];
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch* touch = [touches anyObject];
endPoint = [touch locationInView:self];
[self setNeedsDisplay];
}
I think this will help you.
Related
In my SpriteKit scene, user should be able to draw line with his/her finger. I have a working solution, if the line is long, FPS gets down to 4-6 and the line starts to get polygonal, as the image below:
To draw myline (SKShapeNode*), I collect points of touches movement in an NSMutableArray* noteLinePoints in this way
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
CGPoint touchPoint = [[touches anyObject] locationInNode:self.scene];
SKNode *node = [self nodeAtPoint:touchPoint];
if(noteWritingActive)
{
[noteLinePoints removeAllObjects];
touchPoint = [[touches anyObject] locationInNode:_background];
[noteLinePoints addObject:[NSValue valueWithCGPoint:touchPoint]];
myline = (SKShapeNode*)node;
}
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
if(myline)
{
CGPoint touchPoint = [[touches anyObject] locationInNode:_background];
[noteLinePoints addObject:[NSValue valueWithCGPoint:touchPoint]];
[self drawCurrentNoteLine];
}
}
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
if(myline)
{
myline.name = #"note";
myline = nil;
}
NSLog(#"touch ended");
}
and I draw the line in this way
- (CGPathRef)createPathOfCurrentNoteLine
{
CGMutablePathRef ref = CGPathCreateMutable();
for(int i = 0; i < [noteLinePoints count]; ++i)
{
CGPoint p = [noteLinePoints[i] CGPointValue];
if(i == 0)
{
CGPathMoveToPoint(ref, NULL, p.x, p.y);
}
else
{
CGPathAddLineToPoint(ref, NULL, p.x, p.y);
}
}
return ref;
}
- (void)drawCurrentNoteLine
{
if(myline)
{
SKNode* oldLine = [self childNodeWithName:#"line"];
if(oldLine)
[self removeChildrenInArray:[NSArray arrayWithObject:oldLine]];
myline = nil;
myline = [SKShapeNode node];
myline.name = #"line";
[myline setStrokeColor:[SKColor grayColor]];
CGPathRef path = [self createPathOfCurrentNoteLine];
myline.path = path;
CGPathRelease(path);
[_background addChild:myline];
}
}
How can I fix this problem? because all subsequent lines are all polygonal only, I think because the fps is very low and sampling rate of touches automatically get also very low...
Please note that for the test I used an iPad 3 (my app needs to be working from iPad 2 model with iOS7)
Do not constantly create new SKShapeNodes, there is a bug which is causing your slowdown. Instead, only use 1 SKShapeNode (Or create a bunch but reuse them), and append the path with new info (So there is no need to constantly add the myline to the background)
Alternative:
Use 1 community SKSkapeNode for rendering of the path, then convert the SKShapeNode to a texture with view.textureFromNode, then add an SKSpriteNode with this new texture instead of the shape node
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.
New programmer here trying to take things step by step. I am trying to find a way to draw a circle around each currently touched location on a device. Two fingers on the screen, one circle under each finger.
I currently have the working code to draw a circle at one touch location, but once I lay another finger on the screen, the circle moves to that second touch location, leaving the first touch location empty. and when I add a third, it moves there etc.
Ideally I would like to be able to have up to 5 active circle on the screen, one for each finger.
Here is my current code.
#interface TapView ()
#property (nonatomic) BOOL touched;
#property (nonatomic) CGPoint firstTouch;
#property (nonatomic) CGPoint secondTouch;
#property (nonatomic) int tapCount;
#end
#implementation TapView
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[super touchesBegan:touches withEvent:event];
NSArray *twoTouch = [touches allObjects];
if(touches.count == 1)
{
self.tapCount = 1;
UITouch *tOne = [twoTouch objectAtIndex:0];
self.firstTouch = [tOne locationInView:[tOne view]];
self.touched = YES;
[self setNeedsDisplay];
}
if(touches.count > 1 && touches.count < 3)
{
self.tapCount = 2;
UITouch *tTwo = [twoTouch objectAtIndex:1];
self.secondTouch = [tTwo locationInView:[tTwo view]];
[self setNeedsDisplay];
}
}
-(void)drawRect:(CGRect)rect
{
if(self.touched && self.tapCount == 1)
{
[self drawTouchCircle:self.firstTouch :self.secondTouch];
}
}
-(void)drawTouchCircle:(CGPoint)firstTouch :(CGPoint)secondTouch
{
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetRGBStrokeColor(ctx,0.1,0.1,0.1,1.0);
CGContextSetLineWidth(ctx,10);
CGContextAddArc(ctx,self.firstTouch.x,self.firstTouch.y,30,0.0,M_PI*2,YES);
CGContextStrokePath(ctx);
}
I do have setMultipleTouchEnabled:YES declared in my didFinishLaunchingWithOptions method in the appDelegate.m.
I have attempted to use an if statement in the drawTouchCircle method that changes the self.firstTouch.x to self.secondTouch.x based on a self.tapCount but that seems to break the whole thing, leaving me with no circles at any touch locations.
I'm having an immensely hard time trying to find my issue, and I am aware that it might be something quite simple.
I just wrote some code that seems to work. I've added an NSMutableArray property called circles to the view, which contains a UIBezierPath for each circle.
In -awakeFromNib I setup the array and set self.multipleTouchEnabled = YES - (I think you did this using a reference to the view in your appDelegate.m).
In the view I call this method in the -touchesBegan and -touchesMoved methods.
-(void)setCircles:(NSSet*)touches
{
[_circles removeAllObjects]; //clear circles from previous touch
for(UITouch *t in touches)
{
CGPoint pt= [t locationInView:self];
CGFloat circSize = 200; //or whatever you need
pt = CGPointMake(pt.x - circSize/2.0, pt.y - circSize/2.0);
CGRect circOutline = CGRectMake(pt.x, pt.y, circSize, circSize);
UIBezierPath *circle = [UIBezierPath bezierPathWithOvalInRect:circOutline];
[_circles addObject:circle];
}
[self setNeedsDisplay];
}
Touches ended is:
-(void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event
{
[_circles removeAllObjects];
[self setNeedsDisplay];
}
Then I loop over circles in -drawRect and call [circle stroke] on each one
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
How can I disable touches for a CCRect / sprite after it has been touched?
I have in my init method to set the sprite:
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:#"testAtlas_default.plist"];
sceneSpriteBatchNode = [CCSpriteBatchNode batchNodeWithFile:#"testAtlas_default.png"];
[self addChild:sceneSpriteBatchNode z:0];
dinosaur1_c = [CCSprite spriteWithSpriteFrameName:#"dinosaur1-c.png"];
[sceneSpriteBatchNode addChild:dinosaur1_c];
[dinosaur1_c setPosition:CGPointMake(245.0, winSize.height - 174.0)];
I then create a CGRect using the position and size of the sprite as its parameters in:
-(BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
CGPoint touchLocation = [touch locationInView:[touch view]];
touchLocation = [[CCDirector sharedDirector] convertToGL:touchLocation];
touchLocation = [self convertToNodeSpace:touchLocation];
dinosaur1 = CGRectMake(dinosaur1_c.position.x - (dinosaur1_c.contentSize.width / 2), dinosaur1_c.position.y - (dinosaur1_c.contentSize.height / 2), dinosaur1_c.contentSize.width, dinosaur1_c.contentSize.height);
if( CGRectContainsPoint(dinosaur1, touchLocation) )
{
CCLOG(#"Tapped Dinosaur1_c!");
PLAYSOUNDEFFECT(PUZZLE_SKULL);
// Code to disable touches??
// Tried to resize CGRect in here to (0, 0, 1, 1) to get it away from the original sprite, but did not work. Still was able to tap on CGRect.
// Tried [[CCTouchDispatcher sharedDispatcher] setDispatchEvents:NO];, but disables ALL the sprites instead of just this one.
}
}
I'm able to successfully tap on the sprite to make it play the sound, however I just can't figure out how to disable the CGRect after it is touched. I have tried different methods as commented in the code above. Any ideas or tips are appreciated!
this will also help you
- (void)selectSpriteForTouch:(CGPoint)touchLocation {
for (CCSprite *sprite in _projectiles) {
if (CGRectContainsPoint(sprite.boundingBox, touchLocation)) {
NSLog(#"sprite was touched");
[sprite.parent removeChild:sprite cleanup:YES];
[self removeChild:sprite.parent cleanup:YES];
}
} }
- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
CGPoint touchLocation = [self convertTouchToNodeSpace:touch];
[self selectSpriteForTouch:touchLocation];
NSLog(#"touch was _");
return TRUE; }
Ok so I solved the problem. In case anyone was wondering, I set up a -(BOOL)isTapped in my header file and set it to NO in my init method.
When I check for collisions with the touchpoint and the CGRect, I also check to see if isTapped != YES (meaning it hasnt been tapped yet). In that if statement, I do all the actions as normally would but then set isTapped = YES. Now it will skip over when I tap again. Below is my code with the added bits in between *'s
.h file:
BOOL isTapped;
and in the .m file:
.m:
-(id)init
{
isTapped = NO;
// Rest of init method.
}
-(BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
CGPoint touchLocation = [touch locationInView:[touch view]];
touchLocation = [[CCDirector sharedDirector] convertToGL:touchLocation];
touchLocation = [self convertToNodeSpace:touchLocation];
dinosaur1 = CGRectMake(dinosaur1_c.position.x - (dinosaur1_c.contentSize.width / 2), dinosaur1_c.position.y - (dinosaur1_c.contentSize.height / 2), dinosaur1_c.contentSize.width, dinosaur1_c.contentSize.height);
if( CGRectContainsPoint(dinosaur1, touchLocation) **&& isTapped != YES**)
{
CCLOG(#"Tapped Dinosaur1_c!");
PLAYSOUNDEFFECT(PUZZLE_SKULL);
**isTapped = YES;**
}
else
{
CCLog(#"Already Tapped!");
}
}
Thanks for looking!