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: cocos
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];
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.
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];