0

設定された場所内で複数の SKSpriteNodes を生成しようとしていますが、複数のノードを追加すると、互いの上に生成されますか? これを起こさない方法はありますか?

ノードの新しい場所を取得するためにページを更新する必要があるという問題もあります。ノードがページ上で消えた場合、設定された座標内の新しい場所に生成される方法はありますか?

let rect = CGRectMake(x: 90, y: 360, width: 200, height: 200)
let x = rect.origin.x + CGFloat(arc4random()) % rect.size.width
let y = rect.origin.y + CGFloat(arc4random()) % rect.size.height
let randomPoint = CGPointMake(x, y)
self.redcircle.position = randomPoint
self.addChild(redcircle)
self.bluecircle.position = randomPoint
self.addChild(bluecircle)
4

2 に答える 2

0

それらを別の場所に配置するには、2 つの randomPoint が必要です。1 つの位置で 2 つのノードを使用すると、原因randomPointは常に同じになります。

編集(コメントで質問):

min(x, y) と max(x, y) を使用する必要があります

    let x = random(CGRectGetMinX(self.frame), max: CGRectGetMaxX(self.frame))
    let y = random(CGRectGetMinY(self.frame), max: CGRectGetMaxY(self.frame))

let randomPoint = CGPointMake(x, y)
self.redcircle.position = randomPoint
self.addChild(red circle)

そして、ここでランダム関数:

func random() -> CGFloat {
        return CGFloat(Float(arc4random()) / 0xFFFFFFFF)
    }

    func random(min: CGFloat, max: CGFloat) -> CGFloat {
        return random() * (max - min) + min
    }
于 2015-07-28T10:38:46.633 に答える
0

指定された長方形に基づいてランダムなポイントを生成するメソッドを作成する方が簡単です。または、次のように、指定された長方形内にスプライトを生成するメソッド:

import SpriteKit


class GameScene: SKScene {

   let rect =  CGRect(x: 90, y: 360, width: 200, height: 200)

    override func didMoveToView(view: SKView) {


        let debug = SKSpriteNode(color: SKColor.redColor(), size: rect.size)

        debug.alpha = 0.2

        debug.position = rect.origin

        let origin = SKSpriteNode(color: SKColor.redColor(), size:CGSize(width: 5, height:5))

        debug.addChild(origin)

        self.addChild(debug)

    }

    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {

       let sprite = spawnSpriteAtRandomPositionWithinRect(rect)


       self.addChild(sprite)


       println("Sprite spawned at position x,y( \(sprite.position.x), \(sprite.position.y))")
    }

    func randomBetweenNumbers(firstNum: CGFloat, secondNum: CGFloat) -> CGFloat{

        return CGFloat(arc4random()) / CGFloat(UINT32_MAX) * abs(firstNum - secondNum) + min(firstNum, secondNum)
    }

    func spawnSpriteAtRandomPositionWithinRect(rectangle:CGRect)->SKSpriteNode{


        let x = randomBetweenNumbers(rectangle.origin.x - rectangle.size.width / 2.0 , secondNum: rectangle.origin.x + rectangle.size.width/2.0)
        let y = randomBetweenNumbers(rectangle.origin.y - rectangle.size.height / 2.0 , secondNum: rectangle.origin.y + rectangle.size.height/2.0)

        let sprite = SKSpriteNode(color: SKColor.greenColor(), size:CGSize(width: 30, height: 30))

        sprite.position = CGPoint(x: x, y: y)


        return sprite
    }

}

debugという名前のスプライトは実際には必要ありませんが、与えられた長方形を視覚的に示します。

于 2015-07-28T11:52:59.780 に答える