This is code that I had to update from and outdated blog post
import SpriteKit
class CreateEnemies {
var enemySprites: [SKSpriteNode] = []
static var lowerRate = 120
static var upperRate = 250
func spawnEnemy(targetSprite: SKNode) -> SKSpriteNode {
// create a new enemy sprite
let newEnemy = SKSpriteNode(imageNamed:"sharkshark")
enemySprites.append(newEnemy)
newEnemy.size = CGSize(width: 35, height: 35)
let randomXStart = CGFloat(arc4random_uniform(UInt32(2000 - (-2000)))) + CGFloat(-2000)
let randomYStart = CGFloat(arc4random_uniform(UInt32(2000 - (-2000)))) + CGFloat(-2000)
let xInt = Int(randomXStart)
let yInt = Int(randomYStart)
newEnemy.position = CGPoint(x: xInt, y: yInt)
// Define Constraints for orientation/targeting behavior
let i = enemySprites.count-1
let rangeForOrientation = SKRange(constantValue:CGFloat(M_2_PI*7))
let orientConstraint = SKConstraint.orient(to: targetSprite, offset: rangeForOrientation)
let rangeToSprite = SKRange(lowerLimit: CGFloat(CreateEnemies.lowerRate), upperLimit: CGFloat(CreateEnemies.upperRate))
var distanceConstraint: SKConstraint
// First enemy has to follow spriteToFollow, second enemy has to follow first enemy, ...
if enemySprites.count-1 == 0 {
distanceConstraint = SKConstraint.distance(rangeToSprite, to: targetSprite)
} else {
distanceConstraint = SKConstraint.distance(rangeToSprite, to: enemySprites[i-1])
}
newEnemy.constraints = [orientConstraint, distanceConstraint]
return newEnemy
}
}
I was wondering how I would make the enemies get closer to the target gradually the longer they exist.
I tried changing the variables every 5 seconds using a
let wait5 = SKAction.wait(forDuration: 5)
let getCloser = SKAction.repeatForever(SKAction.sequence([wait5, SKAction.run {self.changeRates()}]))
self.run(getCloser)
and attaching it to run a function
func changeRates() {
CreateEnemies.lowerRate -= 25
CreateEnemies.upperRate -= 25
}
A few things here:
1) your random is based on a square not a circle, so you are going to find your enemies spawning more on the corners than in the center of each side of your screen. I would recommend making a random angle between 0 and 2 pi, a random radius of I am guessing between 0 and 2000, and then setting your position using CGPoint(x:cos(angle) * radius, y:sin(angle) * radius)
2) your lowerRate is going to hit negative in 25 seconds, That may become a problem. I would use a percentage instead:
lowerRate = lowerRateStart * percentage
percentage *= 0.90
This will reduce your sprites 10 percent of their current location, so 90 81 73 64 58 52 47 42 38 34 31 28 25 22 20 18 16 14 13 12 11 10 9 8 7 6 5 4..... then be between 4 and 0 for a while. This basically assures that your number approaches zero, but will never become 0.
3) Your random start and your distance constraint are not correlating correctly, and this may cause problems. I would recommend setting the position somewhere inside of your distance constraint radius, so your rates should be:
let radius = CGFloat(arc4random_uniform(UInt32(upperRate - lowerRate)))
newEnemy.position = CGPoint(x:cos(angle) * radius + lowerRate + targetSprite.x, y:sin(angle) * radius + lowerRate + targetSprite.y)
Related
I have a function that spawns little balls, randomly positioned, on the screen. The problem I face is that I want to distribute the balls randomly, but when I do so, some balls spawn on top of each other. I want to exclude all the positions that are already taken (and maybe a buffer of a few pixels around the balls), but I don't know how to do so. I worked around this by giving the balls a Physicsbody, so they move off from one another if they happen to spawn on top of each other. But I want them to not spawn on top of each other in the first place. My code for now is the following:
spawnedBalls = [Ball]()
level = Int()
func setupLevel() {
let numberOfBallsToGenerate = level * 2
let boundary: CGFloat = 26
let rightBoundary = scene!.size.width - boundary
let topBoundary = scene!.size.height - boundary
while spawnedBalls.count < numberOfBallsToGenerate {
let randomPosition = CGPoint(x: CGFloat.random(in: boundary...rightBoundary), y: CGFloat.random(in: boundary...topBoundary))
let ball = Ball()
ball.position = randomPosition
ball.size = CGSize(width: 32, height: 32)
ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.width)
ball.physicsBody?.affectedByGravity = false
ball.physicsBody?.allowsRotation = false
ball.physicsBody?.categoryBitMask = 1
ball.physicsBody?.collisionBitMask = 1
spawnedBalls.append(ball)
self.addChild(ball)
}
}
I don't know if this problem should be solved by having an array that stores all taken positions, or if I should use some kind of FiledNode, where occupied space can be sort of subtracted, but sadly I am unfamiliar with FieldNodes, so I don't know if that's the right way to face the problem.
Step 1) Replace
let randomPosition = ....
with
let randomPosition = randomPositionInOpenSpace()
Step 2) Write the randomPositionInOpenSpace function:
Idea is:
a) generate a random position
b) is it in open space? if so return that
c) repeat until OK
Then Step 3) write the 'is it in open space' function
For that you need to know if the proposed coordinate is near any of the other balls. For circles, you can test the distance between their centers is greater than (radiuses + margins). Distance between centers is pythagoras: sqrt of the x delta squared plus the y delta squared.
I use the following function to append physicsbodies on tiles from a SKTileMapNode:
static func addPhysicsBody(to tileMap: SKTileMapNode, and tileInfo: String){
let tileSize = tileMap.tileSize
let halfWidth = CGFloat(tileMap.numberOfColumns) / 2 * tileSize.width
let halfHeight = CGFloat(tileMap.numberOfRows) / 2 * tileSize.height
for row in 0..<tileMap.numberOfColumns{
for column in 0..<tileMap.numberOfRows{
let tileDefinition = tileMap.tileDefinition(atColumn: column, row: row)
let isCorrectTile = tileDefinition?.userData?[tileInfo] as? Bool
if isCorrectTile ?? false && tileInfo == "wall"{
let x = CGFloat(column) * tileSize.width - halfWidth
let y = CGFloat(row) * tileSize.height - halfHeight
let tileNode = SKNode()
tileNode.position = CGPoint(x: x, y: y)
tileNode.physicsBody = SKPhysicsBody.init(rectangleOf: tileSize, center: CGPoint(x: tileSize.width / 2, y: tileSize.height / 2))
tileNode.physicsBody!.isDynamic = false
tileNode.physicsBody!.restitution = 0.0
tileNode.physicsBody!.categoryBitMask = Constants.PhysicsCategories.wall
tileNode.physicsBody!.collisionBitMask = Constants.PhysicsCategories.player | Constants.PhysicsCategories.npc | Constants.PhysicsCategories.enemy
nodesForGraph.append(tileNode)
tileMap.addChild(tileNode)
}
}
}
}
However if I use this, I have a physicsbody per tile. I want to connect physicsbodies to bigger ones to get a better performance. I know that this can be with init(bodies: [SKPhysicsBody]). But how can I do that?
How can I find out which body is next to another body to group them?
The physicsbodies in the tileMap aren't all next to each other. Some are big blocks of physicsbodies, some are single physicsbodies with no bodies next to them. So I can't simply put every physicsbody in an array and group them.
Here's an image that shows how it looks like at the moment.
I hope the explanation is clear enough. If not, I will try to explain it better.
Has anyone done this before and can point me in the right direction? I would appreciate any help.
EDIT:
Before I tried this:
static var bodies = [SKPhysicsBody]()
static func addPhysicsBody(to tileMap: SKTileMapNode, and tileInfo: String){
let tileSize = tileMap.tileSize
let halfWidth = CGFloat(tileMap.numberOfColumns) / 2 * tileSize.width
let halfHeight = CGFloat(tileMap.numberOfRows) / 2 * tileSize.height
for column in 0..<tileMap.numberOfColumns{
for row in 0..<tileMap.numberOfRows{
let tileDefinition = tileMap.tileDefinition(atColumn: column, row: row)
let isCorrectTile = tileDefinition?.userData?[tileInfo] as? Bool
if isCorrectTile ?? false && tileInfo == "wall"{
let x = CGFloat(column) * tileSize.width - halfWidth
let y = CGFloat(row) * tileSize.height - halfHeight
let tileNode = SKNode()
tileNode.position = CGPoint(x: x, y: y)
tileNode.physicsBody = SKPhysicsBody.init(rectangleOf: tileSize, center: CGPoint(x: tileSize.width / 2, y: tileSize.height / 2))
tileNode.physicsBody!.isDynamic = false
tileNode.physicsBody!.restitution = 0.0
tileNode.physicsBody!.categoryBitMask = Constants.PhysicsCategories.wall
tileNode.physicsBody!.collisionBitMask = Constants.PhysicsCategories.player | Constants.PhysicsCategories.npc | Constants.PhysicsCategories.enemy
//nodesForGraph.append(tileNode)
bodies.append(tileNode.physicsBody!)
tileMap.addChild(tileNode)
}
}
}
tileMap.physicsBody = SKPhysicsBody(bodies: bodies)
}
But when I do this, the physicsbodies are totally messed up..
I recommend applying a line sweep algorithm to merge the tiles together.
You can do this in four steps;
Iterate through the position of the tiles in your SKTileMap.
Find the tiles that are adjacent to one another.
For each group of adjacent tiles, collect:
a down-left corner coordinate and
an up-right corner coordinate.
Draw a square, and move on to the next group of tiles until you run out of tile coordinates.
The first step: creating an array containing all of your position nodes.
func tilephysics() {
let tilesize = tileMap.tileSize
let halfwidth = CGFloat(tileMap.numberOfColumns) / 2.0 * tilesize.width
let halfheight = CGFloat(tileMap.numberOfRows) / 2.0 * tilesize.height
for col in 0 ..< tileMap.numberOfColumns {
for row in 0 ..< tileMap.numberOfRows {
if (tileMap.tileDefinition(atColumn: col, row: row)?.userData?.value(forKey: "ground") != nil) {
let tileDef = tileMap.tileDefinition(atColumn: col, row: row)!
let tile = SKSpriteNode()
let x = round(CGFloat(col) * tilesize.width - halfwidth + (tilesize.width / 2))
let y = round(CGFloat(row) * tilesize.height - halfheight + (tilesize.height / 2))
tile.position = CGPoint(x: x, y: y)
tile.size = CGSize(width: tileDef.size.width, height: tileDef.size.height)
tileArray.append(tile)
tilePositionArray.append(tile.position)
}
}
}
algorithm()
}
The second and third step: finding adjacent tiles, collecting the two corner coordinates, and adding them to an array:
var dir = [String]()
var pLoc = [CGPoint]()
var adT = [CGPoint]()
func algorithm(){
let width = tileMap.tileSize.width
let height = tileMap.tileSize.height
let rWidth = 0.5 * width
let rHeight = 0.5 * height
var ti:Int = 0
var ti2:Int = 0
var id:Int = 0
var dl:CGPoint = CGPoint(x: 0, y: 0)
var tLE = [CGPoint]()
var tRE = [CGPoint]()
for t in tilePositionArray {
if (ti-1 < 0) || (tilePositionArray[ti-1].y != tilePositionArray[ti].y - height) {
dl = CGPoint(x: t.x - rWidth, y: t.y - rHeight)
}
if (ti+1 > tilePositionArray.count-1) {
tLE.append(dl)
tRE.append(CGPoint(x: t.x + rWidth, y: t.y + rHeight))
} else if (tilePositionArray[ti+1].y != tilePositionArray[ti].y + height) {
if let _ = tRE.first(where: {
if $0 == CGPoint(x: t.x + rWidth - width, y: t.y + rHeight) {id = tRE.index(of: $0)!}
return $0 == CGPoint(x: t.x + rWidth - width, y: t.y + rHeight)}) {
if tLE[id].y == dl.y {
tRE[id] = CGPoint(x: t.x + rWidth, y: t.y + rHeight)
} else {
tLE.append(dl)
tRE.append(CGPoint(x: t.x + rWidth, y: t.y + rHeight))
}
} else {
tLE.append(dl)
tRE.append(CGPoint(x: t.x + rWidth, y: t.y + rHeight))
}
}
ti+=1
}
The fourth step: drawing a rectangle and moving on to the next shape:
for t in tLE {
let size = CGSize(width: abs(t.x - tRE[ti2].x), height: abs(t.y - tRE[ti2].y))
let loadnode = SKNode()
loadnode.physicsBody = SKPhysicsBody(rectangleOf: size)
loadnode.physicsBody?.isDynamic = false
loadnode.physicsBody?.affectedByGravity = false
loadnode.physicsBody?.restitution = 0
loadnode.physicsBody?.categoryBitMask = 2
loadnode.position.x = t.x + size.width / 2
loadnode.position.y = t.y + size.height / 2
scene.addChild(loadnode)
ti2 += 1
}
}
Apply these steps correctly, and you should see that your tiles are merged together in large squares; like so:
Screenshot without visuals for comparison
Screenshot without visuals showing the physicsbodies
I had a lot of fun solving this problem. If I have helped you, let me know.
I only recently started coding and am looking for new challenges. Please reach out to me if you have challenges or projects I could possibly contribute to.
As Knight0fDragon pointed out, there is no way to do exactly what you have asked. Unfortunately, tile maps in SpriteKit leave much to be desired. But you might try this technique to reduce the number of physics bodies.
Idea #1 - Manually Draw Your Physics Bodies
Create your tile map in the editor. Just paint your tile textures onto the map; don't assign any physics bodies to them. Then keep working in the editor to drag Color Sprites (SKSpriteNodes) over parts of your map that need a physics body. Shape the nodes to make the largest rectangle possible for areas that need physics bodies. This works best for for large, flat surfaces like walls, floors, ceilings, platforms, crates, etc. It's tedious but you end up with far fewer physics bodies in your simulation than if you automatically assign bodies to all tiles like you are doing.
Idea #2 - Use No Physics Bodies
This idea would probably require even more work, but you could potentially avoid using physics bodies altogether. First, create your tile map in the editor. Analyze your map to identify which tiles mark a barrier, beyond which the player should not cross. Assign a user data identifier to that type of tile. You would need different categories of identifiers for different types of barriers, and you may also need to design your artwork to fit this approach.
Once your barrier tiles are sufficiently identified, write code which checks the user data value for the tile currently occupied by the player sprite and restrict the sprite's movement accordingly. For example, if the player enters a title that marks an upper boundary, your movement code would not allow the player sprite to move up. Likewise, if the player enters a tile that marks the leftmost boundary, your movement code will not let the player travel left.
You can check out this related post where I basically suggest the same ideas. Unfortunately, SpriteKit's tile maps have no perfect solution for this problem.
I'm trying to make a matching game, where these circles appear randomly in a rectangular area, without overlapping. Here's the spawning function:
func SpawnRed(){
var Red = SKSpriteNode(imageNamed: "Matched_Red")
Red.size = CGSize(width: 50, height: 50)
Red.zPosition = 1
let MinValueX = self.size.width / 3 + 50
let MaxValueX = self.size.width / 1.5 - 50
let MinValueY = self.size.height / 1.5 + 25
let MaxValueY = self.size.height / 6
let SpawnPointX = UInt32(MaxValueX - MinValueX)
let SpawnPointY = UInt32(MaxValueY - MinValueY)
Red.position = CGPointMake(CGFloat(arc4random_uniform(SpawnPointX)) + MinValueY,CGFloat(arc4random_uniform(SpawnPointY)))
self.addChild(Red)
}
But for some reason, I keep getting
"Thread 1: EXC_BAD_INSTRUCTION(code=EXC_1386_INVOP,subcode=0x0)" error.
Can you find the solution? Also, it'll be so helpful if you tell me how to spawn nodes without overlapping.
I'm new to SpriteKit game development. I'm trying give a boss character the ability to cast fireballs in multiple directions (16 fireballs all at once, 360 degree/16 = 22.5 degree apart).
I know how to get him to fire at a certain position by providing the player's current position, but how to get him to fire at 16 different angles regardless of player's position?
Thanks for any help in advance.
First, set up a loop over the angles
let numAngles = 16
var angle:CGFloat = 0
var angleIncr = CGFloat(2 * M_PI) / CGFloat(numAngles)
let strength:CGFloat = 50
for _ in 0..<numAngles {
...
angle += angleIncr
}
In the loop, convert the angle to the corresponding vector components and then create a vector
let dx = strength * cos (angle)
let dy = strength * sin (angle)
let vector = CGVectorMake (dx, dy)
and create a new fireball and apply an impulse to its physics body
let fireball = ...
fireball.position = player.position
fireball.zRotation = angle
// Add a physics body here
fireball.physicsBody?.appyImpulse (vector)
I'm not sure what code you have in place. for shooting. but ill give this a shot. angles in spritekit are in radians and a there are 2*pi radians in a circle. so you just need to do something like this
let fireballs = 16
let threeSixty = CGFloat(M_PI*2)
for i in 1...fireballs {
let angle = (CGFloat(i) / CGFloat(fireballs)) * threeSixty
// do something useful with your angle
}
Im trying to randomly generate nodes on the screen without overlapping so I decided to find the range/distance of each node from each other and continuously randomly generate a position where the range from each node is greater than 100, once the range is over 100 it'll break out of the while loop and add the node to the view
var p2Dp1: CGFloat = 0
var p3Dp1: CGFloat = 0
var p3Dp2: CGFloat = 0
planet1.position = CGPoint(x: Int(arc4random_uniform(220) + 80), y: Int(arc4random_uniform(500) + 100))
while p2Dp1 < 100.0 {
planet2.position = CGPoint(x: Int(arc4random_uniform(220) + 80), y: Int(arc4random_uniform(500) + 100))
p2Dp1 = SDistanceBetweenPoints(planet2.position, p2: planet1.position)
print(" planet 2 distance from 1: \(p2Dp1) ")
}
while p3Dp1 < 100.0 && p3Dp2 < 100.0 {
planet3.position = CGPoint(x: Int(arc4random_uniform(220) + 80), y: Int(arc4random_uniform(500) + 100))
p3Dp1 = SDistanceBetweenPoints(planet3.position, p2: planet1.position)
print(" planet 3 distance from 1: \(p3Dp1) ")
p3Dp2 = SDistanceBetweenPoints(planet3.position, p2: planet2.position)
print(" planet 3 distance from 2: \(p3Dp2) ")
}
self.addChild(planet1)
self.addChild(planet2)
self.addChild(planet3)
it starts by randomly giving the first node(planet1) a position on the view and then randomly give node2(planet2) a position where the distance from planet 1 and 2 are greater than 100. The first while loops seems to be working fine, its the second while loops thats giving me trouble. According to the console, the "&&" operator doesn't seem to be working
Console/Log:
planet 2 distance from 1: 96.1665222413705 planet 2 distance from 1: 185.407658957229 planet 3 distance from 1: 136.30847369111 planet 3 distance from 2: 55.1724568965349 EWWWW WE'RE TOUCHING
I set up the didBeginContact(contact: SKPhysicsContact) where it prints out if contact has happened
this is the method im using to find the distance:
func SDistanceBetweenPoints(p1: CGPoint, p2: CGPoint) -> CGFloat {
return hypot(p2.x - p1.x, p2.y - p1.y);
}
can someone please tell me what I might be doing wrong? I'm planning to add 5 planets in total but just for now im testing it out with 3
The condition of your while loop is:
p3Dp1 < 100.0 && p3Dp2 < 100.0
This means that the while loop will only continue while both conditions are true. As soon as either part of the condition is false (i.e. the distance is greater than 100) the loop will stop executing.
You probably want to change the condition to an or (||), for example:
while p3Dp1 < 100.0 || p3Dp2 < 100.0 {
This will keep running the while loop until both distances are greater than 100.
Change && to ||
You are now saying keep trying while both p2 and p3 are less than 100 so as soon as p2 is greater than 100 the while fails and you stop caring about p3.