Question

I am trying to make a game where a ball is bouncing off a user drawn line. The code for drawing the line is included below and works fine but how would I remove the line once the ball makes contact with it or the player draws a new line?

path = [UIBezierPath bezierPath];
// Start Coords of Line
[path moveToPoint:CGPointMake(pos2x, pos2y)];
[path addLineToPoint:CGPointMake(pos1x, pos1y)];
// End Coords of Line
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.path = [path CGPath];
shapeLayer.strokeColor = [[UIColor whiteColor] CGColor];
shapeLayer.lineWidth = 3.0;
shapeLayer.fillColor = [[UIColor clearColor] CGColor];
[self.view.layer addSublayer:shapeLayer];

Thanks in advance!

Was it helpful?

Solution

When you say this:

[self.view.layer addSublayer:shapeLayer];

...also keep a reference to that shape layer. For example, you might have a property currentShapeLayer:

self.currentShapeLayer = shapeLayer;

Now that you have a reference, you can easily remove the layer:

[self.currentShapeLayer removeFromSuperlayer];

Programming iOS is all about keeping references to things you know you'll need later on. If there are more paths, meaning more shape layers, you will need a more complex, intelligent way of distinguishing which is which and which one you want to remove.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top