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

  • iOS: Open a Calendar app New Event screen with populated date
  • iOS 11 Floating TableView Header
  • With fast enumeration and an NSDictionary, iterating in the order of the keys is not guaranteed – how can I make it so it IS in order?
  • Modified EXIF data doesn't save properly
  • Extend default interactivePopGestureRecognizer beyond screen edge?
  • iPhone - Get Position of UIView within entire UIWindow
  • 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.

    3 Solutions Collect From Internet About “Draw a Line Sprite Between Two Points made by Sprites in Cocos2d”

    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 1×1 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.