Verifying that the scene is occupied by a sprite
I am creating my first iPhone game using Xcode, SpriteKit and Swift. I am new to these technologies, but I am familiar with general programming concepts.
Here is what I am trying to do in English. I want the circles to appear randomly on the screen and then start to expand. However, I don't want the circle to appear at the location where the circle currently exists. I am having trouble defining each position of the circle.
Inside GameScene.swift I have the following code inside doMoveToView:
runAction(SKAction.repeatActionForever(
SKAction.sequence([
SKAction.runBlock(addCircle), SKAction.waitForDuration(3, withRange: 2)]
)))
The part of the code above calls my addCircle method:
func addCircle() {
// Create sprite.
let circle = SKSpriteNode(imageNamed: "grad640x640_circle")
circle.name = "circle"
circle.xScale = 0.1
circle.yScale = 0.1
// Determine where to position the circle.
let posX = random(min: 50, max: 270)
let posY = random(min: 50, max: 518)
// ***Check to see if position is currently occupied by another circle here.
circle.position = CGPoint(x: posX, y: posY)
// Add circle to the scene.
addChild(circle)
// Expand the circle.
let expand = SKAction.scaleBy(2, duration: 0.5)
circle.runAction(expand)
}
The random function above just picks a random number in a given range. How can I check if my random functions are generating a location that is currently occupied by another circle?
I was thinking about using a do..while loop to randomly create a set of x and y coordinates and then check if the circle is at that location, but I can't find how to test this condition. Any help would be greatly appreciated.
source to share
There are several methods that can help you in this regard:
-
(BOOL) intersectsNode: (SKNode*)node
accessible with SKNode and -
CGRectContainsPoint()
as well as methodsCGRectContainsRect()
.
For example, a loop to test for intersection might look like this:
var point: CGPoint
var exit:Bool = false
while (!exit) {
let posX = random(min: 50, max: 270)
let posY = random(min: 50, max: 518)
point = CGPoint(x: posX, y: posY)
var pointFound: Bool = true
self.enumerateChildNodesWithName("circle", usingBlock: {
node, stop in
let sprite:SKSpriteNode = node as SKSpriteNode
if (CGRectContainsPoint(sprite.frame, point))
{
pointFound = false
stop.memory = true
}
})
if (pointFound)
{
exit = true
}
}
//point contains CGPoint where no other circle exists
//Declare new circle at point
source to share