检测2个节点何时在每个轴上相交

时间:2017-08-05 01:48:23

标签: swift sprite-kit

我正在尝试编写一个简单的游戏,你可以通过点击一个戒指(不断变大和变小)在固定环内但我无法弄清楚如何检测两个节点何时相交或何时移动环位于静止环内。有人可以告诉我如果有人在两个节点大小相同或者移动节点在静止节点内时轻敲,我可以如何添加分数。

import SpriteKit
import GameplayKit

class GameScene: SKScene {

    var Circle = SKSpriteNode()
    var Circle2 = SKSpriteNode()

    var GameStarted:Bool = false

    var Path = UIBezierPath()
    var run1 = false
    var called = true
    var intersected = false


    override func didMove(to view: SKView) {
        Circle = SKSpriteNode(imageNamed: "Circle")
        Circle.size = CGSize(width: 100, height: 100)
        Circle.position = CGPoint(x: self.frame.midX, y: self.frame.midY)
        self.addChild(Circle)
        Circle2 = SKSpriteNode(imageNamed: "Circle2")
        Circle2.size = CGSize(width: 760, height: 760)
        Circle2.position = CGPoint(x: self.frame.midX, y: self.frame.midY)
        self.addChild(Circle2)
        Circle.zPosition = 0.1
        Circle2.zPosition = 0.2
        var path = UIBezierPath(arcCenter: CGPoint(x: 15, y: 15), radius: CGFloat(10), startAngle: 0, endAngle: CGFloat(2*Double.pi), clockwise: true)
        UIColor.blue.setStroke()    
    }



    func scaleCircle2(){
        let duration = 5.0
        let scaleAction2 = SKAction.scale(to: CGSize(width: 760, height: 760), duration: TimeInterval(duration))
        let scaleAction = SKAction.scale(to: CGSize(width: 15, height: 15), duration: TimeInterval(duration))
        let pulse = SKAction.sequence([scaleAction,scaleAction2])
        let forever = SKAction.repeatForever(pulse)
        Circle2.run(forever)


   }



    func scaleCircleUP(){
        let duration2 = 0.5
        let initialsize = 100
        let scaleAction3 = SKAction.scale(to: CGSize(width: initialsize + 100, height: initialsize + 100), duration: TimeInterval(duration2))
        Circle.run(scaleAction3)

    }



    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        GameStarted = true
        if GameStarted == true{
            callCircle2()
        }
    }


    func callCircle2(){    //makes sure scaleCircle2 isn't called twice
        if called == true{
            scaleCircle2()
        }
        called = false
    }


}

1 个答案:

答案 0 :(得分:0)

当确定一个圆形物体是否在另一个较大的圆形物体中时,您只需将其半径差异的绝对值与其中心之间的距离进行比较。

extension CGPoint {
    func distanceTo(_ p:CGPoint) -> CGFloat {
        return sqrt(pow((p.x - x), 2) + pow((p.y - y), 2))
    }
}

let dist = Float(Circle.position.distanceTo(Circle2.position))
let radiusDiff = fabsf(Float((Circle.size.width - Circle2.size.width))
if dist < radiusDiff {
    // smaller circle is in larger circle
}

在你的情况下,似乎你永远不会移动他们的起源,你知道哪个对象将是&#34;更小的&#34;一,只需比较它们的半径。