2

For one of my classes I made a javascript game that involve characters that jump to random parts of the screen. I am trying to convert this game to Swift (I am very bad at coding and this is my third day working with Swift).

I got the part where the characters (SKSpriteNode) bounce around the screen. But for some reason I have really struggled with drawing the lines. I tried using UIBezierPath() & CAShapeLayer(). I also tried an SKSpriteNode.

But I haven't been able to draw a line at the proper angle between the original point and the ending point of the characters. Because the characters move to random spots the angle changes all the time and the size of the line also needs to change.

Here's a picture of the Javascript game:

image

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Ryan King
  • 91
  • 1
  • 3
  • 2
    Possible duplicate of [Create a line with two CGPoints SpriteKit Swift](https://stackoverflow.com/questions/31109423/create-a-line-with-two-cgpoints-spritekit-swift) – ndmeiri Jan 09 '18 at 06:31
  • I honestly couldn't get that to work. It won't except "nil" and I tried someone's solution for that, but I still couldn't get it to work. I looked through stackoverflow thoroughly and couldn't get anything to work. – Ryan King Jan 09 '18 at 07:14
  • Try `let path = CGMutablePath()`, `path.move(to: CGPoint(x:100,y:100))`, and `path.addLine(to: CGPoint(x:200,y:200))`. – 0x141E Jan 09 '18 at 20:46

1 Answers1

0

You can use something like this:

var line = SKShapeNode()

func drawLine(from: CGPoint, to: CGPoint){
    line.removeFromParent()
    let path = CGMutablePath()
    path.move(to: from)
    path.addLine(to: to)
    line = SKShapeNode(path: path)
    self.addChild(line)
}

override func update(_ currentTime: TimeInterval) {
    drawLine(from: player.position, to: enemy.position)
}

Here you create a path and add a startpoint to it via path.move(to:). Then you add a line to your other point with path.addLine(to:). Then use the SKShapeNode(path: CGPath) initializer to create a SKShapeNode from the path. The SKShapeNode will present your line in the scene. At the end just add your node to the scene via addChild() and call this function in your update() function to recreate the line when the player or the enemy is moving.

Marcel
  • 472
  • 2
  • 6
  • 19