首页 > 解决方案 > 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.

标签: swiftsprite-kitspriteswift5skspritenode

解决方案


您可以像这样向节点添加约束:

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

当然您可以更改值和中心,.zero其他值仅用于示例。

在这个例子中,绿点有约束,红点没有。

在此处输入图像描述

在此处查看完整示例:https ://github.com/Maetschl/SpriteKitExamples/blob/master/CircularRange/CircularRange/GameScene.swift


推荐阅读