Search code examples
swiftsprite-kitspriteswift5skspritenode

Make Range of Movement SKSpriteNode


So here is my code:

import SpriteKit
import GameplayKit

class GameScene: SKScene {

    var ship1 = [2,1]
    var ship2 = [1,2]

    let jonahSpriteNode = SKSpriteNode(imageNamed: "jonah_spaceship")
    let georgeSpriteNode = SKSpriteNode(imageNamed: "george_spaceship")

    override func didMove(to view: SKView) {
        //var jonahFrames = [SKTexture]()
        jonahSpriteNode.position = CGPoint(x: 30, y: frame.midY)
        jonahSpriteNode.size = CGSize(width: 100.0, height: 100.0)
        addChild(jonahSpriteNode)

        georgeSpriteNode.position = CGPoint(x: 628, y: frame.midY)
        georgeSpriteNode.size = CGSize(width: 100.0, height: 100.0)
        addChild(georgeSpriteNode)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches{
            var touchLocation = touch.location(in: self)
            var angle1 = atan2(jonahSpriteNode.position.y - touchLocation.y , jonahSpriteNode.position.x - touchLocation.x)
            var angle = angle1 - CGFloat(Double.pi / 1)

            let rotate = SKAction.rotate(toAngle: angle, duration: 1.0)
            let move = SKAction.move(to: CGPoint(x: touchLocation.x, y: touchLocation.y), duration: 2.5)
            let sequence = SKAction.sequence([rotate, move])
            jonahSpriteNode.run(sequence)
        }
    }
}

I started a space shooting game and I wanted to set a range of movement so the SKSpriteNode can only move so far. I want to make the range a circular area. Does anyone know a way that I can do this? I searched google and stack overflow but no question are related. Just so you know, I am new to swift. It is probably a really easy answer but I couldn't find one. If anyone has ideas please answer.


Solution

  • You can add a constraint to the node like this:

    func makeCircularRange(to node: SKNode) {
        let range = SKRange(lowerLimit: 0, upperLimit: 100)
        let constraint = SKConstraint.distance(range, to: .zero)
        node.constraints = [constraint]
    }
    

    Sure you can change values and center, .zeroand the other values are for examples only.

    In this example, green dots are with constraint and red doesn't.

    enter image description here

    Take a look for complete example here: https://github.com/Maetschl/SpriteKitExamples/blob/master/CircularRange/CircularRange/GameScene.swift