Objective-C SpriteKit Create dotted line to certain points

。_饼干妹妹 提交于 2019-11-28 13:03:18

Note that all this can be organized better, and I personally don't like SKShapeNode in any shape :) or form, but this is the one way to do it:

#import "GameScene.h"



@implementation GameScene{
    SKShapeNode *line;
}

-(void)didMoveToView:(SKView *)view {
    /* Setup your scene here */

    line = [SKShapeNode node];
    [self addChild:line];
    [line setStrokeColor:[UIColor redColor]];

}

-(void)drawLine:(CGPoint)endingPoint{

    CGMutablePathRef pathToDraw = CGPathCreateMutable();
    CGPathMoveToPoint(pathToDraw, NULL, CGRectGetMidX(self.frame),CGRectGetMidY(self.frame));
    CGPathAddLineToPoint(pathToDraw, NULL, endingPoint.x,endingPoint.y);

    CGFloat pattern[2];
    pattern[0] = 20.0;
    pattern[1] = 20.0;
    CGPathRef dashed =
    CGPathCreateCopyByDashingPath(pathToDraw,NULL,0,pattern,2);

    line.path = dashed;

    CGPathRelease(dashed);
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    /* Called when a touch begins */

    for (UITouch *touch in touches) {
        CGPoint location = [touch locationInNode:self];

        [self drawLine:location];

    }
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    for (UITouch *touch in touches) {
        CGPoint location = [touch locationInNode:self];

        [self drawLine:location];

    }
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{

    line.path = nil;

}

The result is:

Also I don't know how much performant this is, but you can test it, tweak it and improve it. Or even use SKSpriteNode like you said. Happy coding!

EDIT:

I just noticed that you said dotted (not dashed) :)

You have to change pattern to something like:

 pattern[0] = 3.0;
 pattern[1] = 3.0;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!