Sprites and Bounding Box issues - ios

I am making an IOs game for an assignment using cocos2D. So far I am just trying to get all of the menus done, but I am having some issues with bounding box when setting up some of my buttons.
The game starts with the cocos2D logoscreen, then transits into a splash screen for my game, then into the main menu. In the game menu I have 2 buttons: Begin, and Options. Both buttons are working perfectly fine, each makinga transicion to the correct scene.
I am currently working on the options menu scene, where I have a button to take care of volume, a butto to set game difficulty, and a button to go back to main menu. I have been trying to make the back button work, but is not triggering when touched, I placed an NSLog for debugging, and the touches are being detected, just the if statement that checks whether the sprite was touched oris never true. I am puzzled by this, since I am using the same method I used in my main menu (which works). I searched for similar issues before posting, but everything I tried, like altering the parent coordinate system and/or the sprites boundingbox.origin, haven't worked at all.
This is the code for my Options Scene:
#import "OptionsMenu.h"
#implementation OptionsMenu
+(CCScene *) scene
{
// 'scene' is an autorelease object.
CCScene *scene = [CCScene node];
// 'layer' is an autorelease object.
OptionsMenu *layer = [OptionsMenu node];
// add layer as a child to scene
[scene addChild: layer];
// return the scene
return scene;
}
-(id) init
{
if( (self=[super init]) ) {
self.touchEnabled = YES;
self.accelerometerEnabled = YES;
CGSize winSize = [[CCDirector sharedDirector] winSize];
CCSprite *background = [CCSprite spriteWithFile:#"Menu0.png"];
background.position = ccp(winSize.width/2, winSize.height/2);
[self addChild:background z:0];
CCSprite *volumeBar = [CCSprite spriteWithFile:#"VolumeBar.png"];
volumeBar.position = ccp(winSize.width/2, winSize.height/2);
[self addChild:volumeBar z:1];
CCSprite *volumeButton = [CCSprite spriteWithFile:#"VolumeButton.png"];
volumeButton.position = ccp(winSize.width/2, winSize.height/2);
[self addChild:volumeButton z:1];
CCSprite *difficultyButton = [CCSprite spriteWithFile:#"EasyButton.png"];
difficultyButton.position = ccp(winSize.width/2, winSize.height/2-55);
[self addChild:difficultyButton z:1];
CCSprite *backButton = [CCSprite spriteWithFile:#"BackButton.png"];
backButton.position = ccp(winSize.width/12, winSize.height/8);
[self addChild:backButton z:1];
[self scheduleUpdate];
}
return self;
}
- (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];
CCActionInterval *actionInterval = [CCActionInterval actionWithDuration:0.1];
if (CGRectContainsPoint([self.backButton boundingBox], location)) {
[self.backButton setTexture:[[CCTextureCache sharedTextureCache] addImage:#"BackButton.png"]];
id actionCallFunc = [CCCallFunc actionWithTarget:self selector:#selector(goToMainMenu:)];
[self.background runAction: [CCSequence actions: actionInterval, actionCallFunc, nil]];
}
else if (CGRectContainsPoint([self.difficultyButton boundingBox], location)) {
[self.volumeButton setTexture:[[CCTextureCache sharedTextureCache] addImage:#"VolumeButton.png"]];
}
}
}
- (void)ccTouchesBegan:(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]];
NSLog(#"Touch");
//missileButton* missileButton;
location = [[CCDirector sharedDirector] convertToGL: location];
if (CGRectContainsPoint([self.backButton boundingBox], location))
{
[self.backButton setTexture:[[CCTextureCache sharedTextureCache]addImage:#"BackButtonPressed.png"]];
NSLog(#"BackButtonTouched");
}
else if (CGRectContainsPoint([self.volumeButton boundingBox], location))
[self.volumeButton setTexture:[[CCTextureCache sharedTextureCache]addImage:#"VolumeButtonPressed.png"]];
}
}
-(void) goToMainMenu:(id) sender
{
[[CCDirector sharedDirector] replaceScene: [CCTransitionSlideInR transitionWithDuration:2 scene:[MainMenu node]]];
}
#end
I would appreciate any help in solving this issue.

Your self.backButton is never defined. Change your init function to the following (I'm assuming all of your CCSprite defines are actually properties:
-(id) init
{
if( (self=[super init]) ) {
self.touchEnabled = YES;
self.accelerometerEnabled = YES;
CGSize winSize = [[CCDirector sharedDirector] winSize];
_background = [CCSprite spriteWithFile:#"Menu0.png"];
_background.position = ccp(winSize.width/2, winSize.height/2);
[self addChild:_background z:0];
_volumeBar = [CCSprite spriteWithFile:#"VolumeBar.png"];
_volumeBar.position = ccp(winSize.width/2, winSize.height/2);
[self addChild:_volumeBar z:1];
_volumeButton = [CCSprite spriteWithFile:#"VolumeButton.png"];
_volumeButton.position = ccp(winSize.width/2, winSize.height/2);
[self addChild:_volumeButton z:1];
_difficultyButton = [CCSprite spriteWithFile:#"EasyButton.png"];
_difficultyButton.position = ccp(winSize.width/2, winSize.height/2-55);
[self addChild:_difficultyButton z:1];
_backButton = [CCSprite spriteWithFile:#"BackButton.png"];
_backButton.position = ccp(winSize.width/12, winSize.height/8);
[self addChild:_backButton z:1];
[self scheduleUpdate];
}
return self;
}

Another approach would be to use CCMenu and CCMenuItemSprite for all of your buttons. These classes make simple buttons for menus much easier to implement. Most/all of the touch handling is done for you and there are variants that use selectors or blocks for handling the button press.
This would save you a lot of code, and trouble.

Related

Sprite touch detection

Have a question here. I created a couple sprites (with tags) in my (id)init function, and then merely trying to detect which sprite was touched? A snippet of the code from my init function is pasted below.
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:#"blue_sheet.plist"];
//create a sprite batch node
CCSpriteBatchNode *TrainerSprites = [CCSpriteBatchNode batchNodeWithFile:#"blue_sheet.png"];
[self addChild:TrainerSprites z:1];
//create a sprite from that node
CCSprite *Horse = [CCSprite spriteWithSpriteFrameName:#"horse_blue.png"];
[TrainerSprites addChild:Horse z:1 tag:1];
//Horse.position = ccp(winSize.width/5, winSize.height/2);
[Horse setScaleX: 138.5/Horse.contentSize.width];
[Horse setScaleY: 80/Horse.contentSize.height];
//create a sprite from that node
CCSprite *Cow = [CCSprite spriteWithSpriteFrameName:#"cow_blue.png"];
[TrainerSprites addChild:Cow z:1 tag:2];
//Cow.position = ccp(winSize.width/2, winSize.height/2);
[Cow setScaleX: 126/Cow.contentSize.width];
[Cow setScaleY: 100/Cow.contentSize.height];
Horse.position = ccp(4*winSize.width/5, winSize.height/2);
Cow.position = ccp(winSize.width/5, winSize.height/2);
CGRect pos1 = CGRectMake(Cow.position.x, Cow.position.y, 200, 100);
CGRect pos2 = CGRectMake(Horse.position.x, Horse.position.y, 200, 100);
self.touchEnabled = YES;
All looks fine... and the sprites appear where they are supposed to. When I touch anywhere on screen my ccTouchBegan function fires. Not seeing anything happen with the CGRect and I suppose I need to determine which one fired by the assigned tag. Yes indeedy, I know I'm missing code, I just cannot locate good solid documentation anywhere how to do this seemingly basic ios functionality. I assume the "sprite touch detection" code should reside inside the ccTouchBegan function? Any help or guidance sincerely appreciated. :)
Another approach could be to subclass CCSprite and implement the TargetedTouchDelegate.
Something like:
#interface AnimalSprite:CCSprite<CCTargetedTouchDelegate>
The advantage of this approach is that you wont have to do a lot of "If" checks in the layer where you are adding the sprites. The link provides the method that you must implement in orer to implement the protocol and where and how you could register with the touch dispatcher.
to detect the sprite touch you can use this
declare CCSprite *Cow in your .h section
and in .m section use this
in init method
//create a sprite from that node
Cow = [CCSprite spriteWithSpriteFrameName:#"cow_blue.png"];
[TrainerSprites addChild:Cow z:1 tag:2];
//Cow.position = ccp(winSize.width/2, winSize.height/2);
[Cow setScaleX: 126/Cow.contentSize.width];
[Cow setScaleY: 100/Cow.contentSize.height];
in touches began method
-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch * touch =[touches anyObject];
CGPoint location=[touch locationInView:[touch view]];
location =[[CCDirector sharedDirector] convertToGL:location];
if (CGRectContainsPoint( [Cow boundingBox], location)) {
/* CCScene *scene = [CCScene node];
[scene addChild:[ClassicScene node]];
[[CCDirector sharedDirector] replaceScene:scene];*/
}
}

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.

Linking HUDLayer to GameplayLayer properly

I'm trying to pass the touch location from GameplayLayer to HUDLayer to see if user presses control buttons.
HudLayer.mm
-(void) handleTouchAtLocation:(CGPoint) location {
NSLog(#"Touch passed to HUD");
}
Gameplay.mm
enum {
kHudLayer = 2;
};
+(CCScene *) scene {
CCScene *scene = [CCScene node];
HudLayer *hud = [HudLayer node];
[scene addChild:hud z:kHudLayer];
GameplayLayer *layer = [GameplayLayer node];
[scene addChild:layer];
return scene;
}
-(void) ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
for( UITouch *touch in touches ) {
CGPoint location = [touch locationInView: [touch view]];
location = [[CCDirector sharedDirector] convertToGL: location];
[self handTouchAtPoint:(location)];
}
}
-(void) handleTouchAtPoint:(CGPoint)location {
NSLog(#"Touch At Point");
HudLayer *h1 = (HudLayer *)[self.parent getChildWithTag:kHudLayer];
[h1 handleTouchAtLocation:location];
}
HudLayer.h is imported in GameplayLayer.h.
I'm getting the "Touch At Point" log but it's not going through to HUD layer for some reason..
The only explanation is that self.parent has no child with the tag kHudLayer. If you set a breakpoint in handleTouchAtPoint you'll notice h1 being nil after the getChildWithTag line did execute.

Undisplayed view crash in cocos2D

There are no errors or warning but this crashes when I try and switch to the view:
#import "Level1.h"
#import "LevelSelect.h"
#import "GameOver.h"
enum {
kTagPlayer, kTagComputer
};
#implementation Level1
+(id) scene {
CCScene *scene = [CCScene node];
Level1 *layer = [Level1 node];
[scene addChild: layer];
return scene;
}
-(id) init {
if( (self=[super init] )) {
CCSprite *player = [CCSprite spriteWithFile:#"Icon_Small_50.png"];
player.position = ccp(60, 60);
[self addChild:player z:2 tag:kTagPlayer];
CCSprite *computer = [CCSprite spriteWithFile:#"Icon_Small.png"];
computer.position = ccp(440, 160);
[self addChild:computer z:1 tag:kTagComputer];
[computer runAction:[CCMoveTo actionWithDuration:3.0
position:ccp(player.position.x, player.position.y)]];
self.isTouchEnabled = YES;
[self schedule:#selector(SpritesDidColide)
interval:.01];
}
return self;
}
-(void) ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *myTouch = [touches anyObject];
CGPoint point = [myTouch locationInView:[myTouch view]];
point = [[CCDirector sharedDirector] convertToGL:point];
CCNode *player = [self getChildByTag:kTagPlayer];
[player setPosition:point];
CCNode *computer = [self getChildByTag:kTagComputer];
[computer runAction:[CCMoveTo actionWithDuration:3.0
position:ccp(player.position.x, player.position.y)]];
}
-(void) ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *myTouch = [touches anyObject];
CGPoint point = [myTouch locationInView:[myTouch view]];
point = [[CCDirector sharedDirector] convertToGL:point];
CCNode *player = [self getChildByTag:kTagPlayer];
[player setPosition:point];
CCNode *computer = [self getChildByTag:kTagComputer];
[computer runAction:[CCMoveTo actionWithDuration:3.0
position:ccp(player.position.x, player.position.y)]];
}
-(void) SpritesDidCollide {
CCNode *player = [self getChildByTag:kTagPlayer];
CCNode *computer = [self getChildByTag:kTagComputer];
float xDif = computer.position.x - player.position.x;
float yDif = computer.position.y - player.position.y;
float distance = sqrt(xDif * xDif + yDif * yDif);
if (distance < 45) {
[self unschedule:#selector(SpritesDidCollide)];
[[CCDirector sharedDirector] replaceScene:[CCTransitionScene transitionWithDuration:1 scene:[GameOver node]]];
}
}
#end
And here is what displays in the Console:
* Assertion failure in -[CCTimer initWithTarget:selector:interval:], /Users/GLaDOS/Documents/Xcode 4 Projects/2DPlatformer/2DPlatformer/libs/cocos2d/CCScheduler.m:110
2012-02-17 19:13:07.460 2DPlatformer[709:707] Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Signature not found for selector - does it have the following form? -(void) name: (ccTime) dt'
** First throw call stack:
(0x37f1d8bf 0x31a031e5 0x37f1d7b9 0x31e1c3b3 0x46565 0x4843f 0x3402d 0x948d3 0x32249 0x93a23 0x37f20814 0x37e7b7e1 0x2de31 0x2bdc9 0x37e77435 0x7087f 0x71019 0x727ff 0x352ef50f 0x352eef01 0x352d54ed 0x352d4d2d 0x379f2df3 0x37ef1553 0x37ef14f5 0x37ef0343 0x37e734dd 0x37e733a5 0x379f1fcd 0x35303743 0x912c7 0x2300)
terminate called throwing an exceptionkill
Current language: auto; currently objective-c
quit
Program ended with exit code: 0
I believe the schedule method will trigger a call back to a selector of the form:
-(void) SpritesDidCollide:(ccTime) dt{
// do your thing here.
}
and change the selector to
[self schedule:#selector(SpritesDidCollide:) interval:.01];

Draw a Line Sprite Between Two Points made by Sprites in Cocos2d

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.

Resources