确保节点可见

时间:2015-10-04 01:16:06

标签: ios swift sprite-kit swift2 skspritenode

所以我有这个精灵套装游戏,用swift 2编码。游戏包括从屏幕上掉下来的这些彩色圆圈(绿色,红色,紫色,黄色,蓝色),从相同的高度开始,但从不同的宽度。当圆圈击中屏幕的底部时,会调用可敬的方法。我遇到的问题是,随机x位置有时可以将圆圈的一半切掉,因为它位于屏幕的另一侧。如何防止圆圈夹在屏幕的一侧?以下是圆圈点击屏幕底部时调用的方法。

    func changeGreen(){

    Green.position.y = frame.size.height * 0.9

    let PositionX = arc4random_uniform(UInt32(self.frame.width))

    Green.position.x = CGFloat(PositionX)

}

func changeRed(){

    Red.position.y = frame.size.height * 0.9

    let PositionX = arc4random_uniform(UInt32(self.frame.width))

    Red.position.x = CGFloat(PositionX)

}

func changeBlue()   {

    Blue.position.y = frame.size.height * 0.9

    let PositionX = arc4random_uniform(UInt32(self.frame.width))

    Blue.position.x = CGFloat(PositionX)

}

func changeYellow() {

    Yellow.position.y = frame.size.height * 0.9

    let PositionX = arc4random_uniform(UInt32(self.frame.width))

    Yellow.position.x = CGFloat(PositionX)

}

func changePurple() {

    Purple.position.y = frame.size.height * 0.9

    let PositionX = arc4random_uniform(UInt32(self.frame.width))

    Purple.position.x = CGFloat(PositionX)

}

2 个答案:

答案 0 :(得分:0)

假设position.x是圆圈的中心,我认为这样的事情可能会起作用:

let maxX = 350    // this is your frame width
let radius = 50   // radius of the circle
var positionX = Int(arc4random_uniform(UInt32(maxX - radius))) // max position of x is taken care of here


let pointsFromLeft = positionX - radius
if pointsFromLeft < 0 {
    positionX -=  pointsFromLeft // move to the right if necessary
}

答案 1 :(得分:0)

您必须从radius的两端偏移圆圈的frame,以便圈子永远不会被剪裁。

let radius = 20 // radius of your circle
let positionX = radius + arc4random_uniform(UInt32(self.frame.width - 2 * radius))