Procedural Level Generation With Cellular Automaton In Swift - swift

Is there a easy way to create a procedural level with a cellular automaton in swift/SpriteKit(library?)? I want to create a 'cave' with 11 fields in the height and 22 width. These should be randomly created and every field without a wall should be reached.
I just found a documentation using Objective-C, which I am not familiar with. I spend quite some time trying to understand the code and follow the example without success.
PS: If there is an easier way I appreciate some algorithms

I made a Playground where you can experiment
//: Playground - noun: a place where people can play
import UIKit
import SpriteKit
import XCPlayground
class Cave {
var cellmap:[[Bool]]
let chanceToStartAlive = 35
let deathLimit = 3
let birthLimit = 4
var xCell = 40 // number of cell in x axes
var yCell = 20 // number of cell in y axes
var wCell = 20 // cell width
var hCell = 20 // cell height
init(){
cellmap = Array(count:yCell, repeatedValue:
Array(count:xCell, repeatedValue:false))
cellmap = self.initialiseMap(xCell, yIndex:yCell)
}
func initialiseMap(xIndex:Int, yIndex:Int) -> [[Bool]]{
var map:[[Bool]] = Array(count:yIndex, repeatedValue:
Array(count:xIndex, repeatedValue:false))
for y in 0...(yIndex - 1) {
for x in 0...(xIndex - 1) {
let diceRoll = Int(arc4random_uniform(100))
if diceRoll < chanceToStartAlive {
map[y][x] = true
} else {
map[y][x] = false
}
}
}
return map
}
func addSprite(scene:SKScene){
for (indexY, row) in cellmap.enumerate(){
for (indexX, isWall) in row.enumerate(){
if isWall {
let wall = SKSpriteNode(color: UIColor.redColor(), size: CGSize(width: wCell, height: hCell))
wall.position = CGPoint(x: (indexX * wCell) + (wCell / 2) , y: (indexY * hCell) + (hCell / 2) )
scene.addChild(wall)
}
}
}
}
func countAliveNeighbours(x:Int, y:Int) -> Int{
var count = 0
var neighbour_x = 0
var neighbour_y = 0
for i in -1...1 {
for j in -1...1 {
neighbour_x = x + j
neighbour_y = y + i
if(i == 0 && j == 0){
} else if(neighbour_x < 0 || neighbour_y < 0 || neighbour_y >= cellmap.count || neighbour_x >= cellmap[0].count){
count = count + 1
} else if(cellmap[neighbour_y][neighbour_x]){
count = count + 1
}
}
}
return count
}
func applyRules(){
var newMap:[[Bool]] = Array(count:yCell, repeatedValue:
Array(count:xCell, repeatedValue:false))
for y in 0...(cellmap.count - 1) {
for x in 0...(cellmap[0].count - 1) {
let nbs = countAliveNeighbours( x, y: y);
if(cellmap[y][x]){
if(nbs < deathLimit){
newMap[y][x] = false;
}
else{
newMap[y][x] = true;
}
} else{
if(nbs > birthLimit){
newMap[y][x] = true;
}
else{
newMap[y][x] = false;
}
}
}
}
cellmap = newMap
}
}
let view:SKView = SKView(frame: CGRectMake(0, 0, 1024, 768))
XCPShowView("Live View", view: view)
let scene:SKScene = SKScene(size: CGSizeMake(1024, 768))
scene.scaleMode = SKSceneScaleMode.AspectFit
let aCave = Cave()
aCave.applyRules()
aCave.applyRules()
aCave.addSprite(scene)
view.presentScene(scene)

Updated the playground code for Xcode 8 and Swift 3. I swapped the X and Y cell count since you will likely see the view in a "portrait" orientation.
Remember to open the Assistant Editor to view the results. It also takes a little while to execute, so give it a couple of minutes to run the algorithm.
//: Playground - noun: a place where people can play
import UIKit
import SpriteKit
import XCPlayground
import PlaygroundSupport
class Cave {
var cellmap:[[Bool]]
let chanceToStartAlive = 35
let deathLimit = 3
let birthLimit = 4
var xCell = 20 // number of cell in x axes
var yCell = 40 // number of cell in y axes
var wCell = 20 // cell width
var hCell = 20 // cell height
init(){
cellmap = Array(repeating:
Array(repeating:false, count:xCell), count:yCell)
cellmap = self.initialiseMap(xIndex: xCell, yIndex:yCell)
}
func initialiseMap(xIndex:Int, yIndex:Int) -> [[Bool]]{
var map:[[Bool]] = Array(repeating:
Array(repeating:false, count:xIndex), count:yIndex)
for y in 0...(yIndex - 1) {
for x in 0...(xIndex - 1) {
let diceRoll = Int(arc4random_uniform(100))
if diceRoll < chanceToStartAlive {
map[y][x] = true
} else {
map[y][x] = false
}
}
}
return map
}
func addSprite(scene:SKScene){
for (indexY, row) in cellmap.enumerated(){
for (indexX, isWall) in row.enumerated(){
if isWall {
let wall = SKSpriteNode(color: UIColor.red, size: CGSize(width: wCell, height: hCell))
wall.position = CGPoint(x: (indexX * wCell) + (wCell / 2) , y: (indexY * hCell) + (hCell / 2) )
scene.addChild(wall)
}
}
}
}
func countAliveNeighbours(x:Int, y:Int) -> Int{
var count = 0
var neighbour_x = 0
var neighbour_y = 0
for i in -1...1 {
for j in -1...1 {
neighbour_x = x + j
neighbour_y = y + i
if(i == 0 && j == 0){
} else if(neighbour_x < 0 || neighbour_y < 0 || neighbour_y >= cellmap.count || neighbour_x >= cellmap[0].count){
count = count + 1
} else if(cellmap[neighbour_y][neighbour_x]){
count = count + 1
}
}
}
return count
}
func applyRules(){
var newMap:[[Bool]] = Array(repeating:
Array(repeating:false, count:xCell), count:yCell)
for y in 0...(cellmap.count - 1) {
for x in 0...(cellmap[0].count - 1) {
let nbs = countAliveNeighbours( x: x, y: y);
if(cellmap[y][x]){
if(nbs < deathLimit){
newMap[y][x] = false;
}
else{
newMap[y][x] = true;
}
} else{
if(nbs > birthLimit){
newMap[y][x] = true;
}
else{
newMap[y][x] = false;
}
}
}
}
cellmap = newMap
}
}
let view:SKView = SKView(frame: CGRect(x: 0, y: 0, width: 768, height: 1024))
let scene:SKScene = SKScene(size: CGSize(width: 768, height: 1024))
scene.scaleMode = SKSceneScaleMode.aspectFit
PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView = view
let aCave = Cave()
aCave.applyRules()
aCave.applyRules()
aCave.addSprite(scene: scene)
view.presentScene(scene)

Related

SKTexture: Error loading image resource: "Tile_-4412407809"

I'm trying to find out what is causing this Tile_xxxxx name to be some sort of long random number in this code.
SKTexture: Error loading image resource: "Tile_-4412407809"
The code related to it is in this tutorial: https://www.raywenderlich.com/54-how-to-make-a-game-like-candy-crush-with-spritekit-and-swift-part-2
The Tile name is set in the swift file GameScene.swift line 144.
let name = String(format: "Tile_%ld", value)
and it's probably best if I put the code from the file in here. Something is setting "value" to something it can't use. But what? Where is it getting hashValue from
var value = topLeft.hashValue
import SpriteKit
import GameplayKit
class GameScene: SKScene {
// Sound FX
let swapSound = SKAction.playSoundFileNamed("Chomp.wav", waitForCompletion: false)
let invalidSwapSound = SKAction.playSoundFileNamed("Error.wav", waitForCompletion: false)
let matchSound = SKAction.playSoundFileNamed("Ka-Ching.wav", waitForCompletion: false)
let fallingCookieSound = SKAction.playSoundFileNamed("Scrape.wav", waitForCompletion: false)
let addCookieSound = SKAction.playSoundFileNamed("Drip.wav", waitForCompletion: false)
var level: Level!
let tilesLayer = SKNode()
let cropLayer = SKCropNode()
let maskLayer = SKNode()
let tileWidth: CGFloat = 32.0
let tileHeight: CGFloat = 36.0
let gameLayer = SKNode()
let cookiesLayer = SKNode()
var swipeHandler: ((Swap) -> Void)?
private var swipeFromColumn: Int?
private var swipeFromRow: Int?
private var selectionSprite = SKSpriteNode()
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder) is not used in this app")
}
override init(size: CGSize) {
super.init(size: size)
anchorPoint = CGPoint(x: 0.5, y: 0.5)
// This is the Witches background image
let background = SKSpriteNode(imageNamed: "Background")
background.size = size
addChild(background)
addChild(gameLayer)
gameLayer.isHidden = true
let layerPosition = CGPoint(
x: -tileWidth * CGFloat(numColumns) / 2,
y: -tileHeight * CGFloat(numRows) / 2)
tilesLayer.position = layerPosition
maskLayer.position = layerPosition
cropLayer.maskNode = maskLayer
gameLayer.addChild(tilesLayer)
gameLayer.addChild(cropLayer)
cookiesLayer.position = layerPosition
cropLayer.addChild(cookiesLayer)
let _ = SKLabelNode(fontNamed: "GillSans-BoldItalic")
}
func addSprites(for cookies: Set<Cookie>) {
for cookie in cookies {
let sprite = SKSpriteNode(imageNamed: cookie.cookieType.spriteName)
sprite.size = CGSize(width: tileWidth, height: tileHeight)
sprite.position = pointFor(column: cookie.column, row: cookie.row)
cookiesLayer.addChild(sprite)
cookie.sprite = sprite
// Give each cookie sprite a small, random delay. Then fade them in.
sprite.alpha = 0
sprite.xScale = 0.5
sprite.yScale = 0.5
sprite.run(
SKAction.sequence([
SKAction.wait(forDuration: 0.25, withRange: 0.5),
SKAction.group([
SKAction.fadeIn(withDuration: 0.25),
SKAction.scale(to: 1.0, duration: 0.25)
])
]))
}
}
func addTiles() {
for row in 0..<numRows {
for column in 0..<numColumns {
if level.tileAt(column: column, row: row) != nil {
let tileNode = SKSpriteNode(imageNamed: "MaskTile")
tileNode.size = CGSize(width: tileWidth, height: tileHeight)
tileNode.position = pointFor(column: column, row: row)
maskLayer.addChild(tileNode)
}
}
}
for row in 0...numRows {
for column in 0...numColumns {
let topLeft = (column > 0) && (row < numRows)
&& level.tileAt(column: column - 1, row: row) != nil
let bottomLeft = (column > 0) && (row > 0)
&& level.tileAt(column: column - 1, row: row - 1) != nil
let topRight = (column < numColumns) && (row < numRows)
&& level.tileAt(column: column, row: row) != nil
let bottomRight = (column < numColumns) && (row > 0)
&& level.tileAt(column: column, row: row - 1) != nil
var value = topLeft.hashValue
value = value | topRight.hashValue << 1
value = value | bottomLeft.hashValue << 2
value = value | bottomRight.hashValue << 3
// Values 0 (no tiles), 6 and 9 (two opposite tiles) are not drawn.
if value != 0 && value != 6 && value != 9 {
let name = String(format: "Tile_%ld", value)
//print(name)
let tileNode = SKSpriteNode(imageNamed: name)
tileNode.size = CGSize(width: tileWidth, height: tileHeight)
var point = pointFor(column: column, row: row)
point.x -= tileWidth / 2
point.y -= tileHeight / 2
tileNode.position = point
tilesLayer.addChild(tileNode)
}
}
}
}
Fixed.
Change
var value = topLeft.hashable
value = value | topRight.hashable << 1
value = value | bottomLeft.hashable << 2
value = value | bottomRight.hashable << 3
to
var value = (topLeft ? 1 : 0)
value = value | (topRight ? 1 : 0) << 1
value = value | (bottomLeft ? 1 : 0) << 2
value = value | (bottomRight ? 1 : 0) << 3

iOS Charts - Display highest and lowest value for CandleStick charts

I'm trying to create a candlestick chart using Charts
As you guys can notice from my screenshot, the chart only shows the highest and lowest values instead of displaying the values for all the candles. Is there any way I can implement that with the Charts framework?
Thanks in advance.
If you want to display only highest and lowest values, you need to implement you own renderer inherited from CandleStickChartRenderer. In fact you just need to override one function drawValues(context: CGContext).
I have made some example which contain a hundred lines of code, but in fact my custom code contains about thirty lines.
class MyCandleStickChartRenderer: CandleStickChartRenderer {
private var _xBounds = XBounds() // Reusable XBounds object
private var minValue: Double
private var maxValue: Double
// New constructor
init (view: CandleStickChartView, minValue: Double, maxValue: Double) {
self.minValue = minValue
self.maxValue = maxValue
super.init(dataProvider: view, animator: view.chartAnimator, viewPortHandler: view.viewPortHandler)
}
// Override draw function
override func drawValues(context: CGContext)
{
guard
let dataProvider = dataProvider,
let candleData = dataProvider.candleData
else { return }
guard isDrawingValuesAllowed(dataProvider: dataProvider) else { return }
var dataSets = candleData.dataSets
let phaseY = animator.phaseY
var pt = CGPoint()
for i in 0 ..< dataSets.count
{
guard let dataSet = dataSets[i] as? IBarLineScatterCandleBubbleChartDataSet
else { continue }
let valueFont = dataSet.valueFont
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
let valueToPixelMatrix = trans.valueToPixelMatrix
_xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator)
let lineHeight = valueFont.lineHeight
let yOffset: CGFloat = lineHeight + 5.0
for j in stride(from: _xBounds.min, through: _xBounds.range + _xBounds.min, by: 1)
{
guard let e = dataSet.entryForIndex(j) as? CandleChartDataEntry else { break }
guard e.high == maxValue || e.low == minValue else { continue }
pt.x = CGFloat(e.x)
if e.high == maxValue {
pt.y = CGFloat(e.high * phaseY)
} else if e.low == minValue {
pt.y = CGFloat(e.low * phaseY)
}
pt = pt.applying(valueToPixelMatrix)
if (!viewPortHandler.isInBoundsRight(pt.x))
{
break
}
if (!viewPortHandler.isInBoundsLeft(pt.x) || !viewPortHandler.isInBoundsY(pt.y))
{
continue
}
if dataSet.isDrawValuesEnabled
{
// In this part we draw min and max values
var textValue: String?
var align: NSTextAlignment = .center
if e.high == maxValue {
pt.y -= yOffset
textValue = "← " + String(maxValue)
align = .left
} else if e.low == minValue {
pt.y += yOffset / 5
textValue = String(minValue) + " →"
align = .right
}
if let textValue = textValue {
ChartUtils.drawText(
context: context,
text: textValue,
point: CGPoint(
x: pt.x,
y: pt.y ),
align: align,
attributes: [NSAttributedStringKey.font: valueFont, NSAttributedStringKey.foregroundColor: dataSet.valueTextColorAt(j)])
}
}
}
}
}
}
Do not forget use you custom renderer for you chart. ;)
myCandleStickChartView.renderer = MyCandleStickChartRenderer(view: myCandleStickChartView, minValue: 400, maxValue: 1450)

Use a pan gesture to select multiple cells in a CollectionView

I'm just a beginner in Swift but I was trying to implement this particular feature in a project of mine (word search puzzle): selecting multiple cells with a pan gesture. Each of my cells contains a label that holds a single character. I'd like to get all the letters the user wants to select through a pan gesture. Currently I'm doing this by calculating the distance from the center of each cell to the line passing though points a (touch began) and b (touch ended) and taking into consideration only the cells that lie close enough to that line. This works fine most of the time but it's still prone to errors and it is sure to lead to user dissatisfaction. Could you suggest a simpler way of doing this?
Thanks.
Some code:
func getGridInfo(){
for i in 0...numberOfCells-1{
let indPath = IndexPath(row:i, section:0);
let cell = collectionView?.cellForItem(at: indPath) as? CustomCell;
let frameRect = collectionView?.convert((cell?.frame)!, to: self.view);
coordinates[i] = (cell?.label.text, frameRect?.midX, frameRect?.midY) as? (String, CGFloat, CGFloat);
}
}
#objc func handlePan(touch: UIPanGestureRecognizer){
let touchPoint = touch.location(in: self.view)
switch touch.state{
case .began:
if let line = curLine{
line.removeFromSuperlayer();
}
firstPoint = touchPoint;
case .ended:
secondPoint = touchPoint;
guard let fP = firstPoint,
let sP = secondPoint else {
print("Something went wrong..");
return;
}
let word = getCloseLetters(start:fP, end:sP);
if (words.contains(word) || words.contains(String(word.reversed()))){
playSound(soundUrl: correctUrlSoundFx);
foundWordsLabel.text = word;
foundWordsLabel.textColor = UIColor.green;
// to do: update score
}else{
playSound(soundUrl: incorrectUrlSoundFx);
let attributedString = NSMutableAttributedString(string:word);
attributedString.addAttribute(NSAttributedStringKey.strikethroughStyle, value:2, range: NSMakeRange(0, attributedString.length));
foundWordsLabel.attributedText = attributedString;
foundWordsLabel.textColor = UIColor.red;
}
curLine = addLine(fromPoint: firstPoint!, toPoint: secondPoint!, width:20);
default:
return;
}
func getCloseLetters(start:CGPoint, end:CGPoint) -> String{
var letters = "";
for i in 0...numberOfCells-1{
let tuple = coordinates[i]!;
let x = tuple.1;
let y = tuple.2;
if (checkIfPointIsCloseOrOnTheLine(start: start, end: end, aPoint: CGPoint(x:x,y:y)) == true){
letters += tuple.0;
}
}
return letters;
}
func distanceFromPoint(p: CGPoint, v: CGPoint, w: CGPoint) -> CGFloat {
let pv_dx = p.x - v.x;
let pv_dy = p.y - v.y;
let wv_dx = w.x - v.x;
let wv_dy = w.y - v.y;
let dot = pv_dx * wv_dx + pv_dy * wv_dy;
let len_sq = wv_dx * wv_dx + wv_dy * wv_dy;
let param = dot / len_sq;
var int_x, int_y: CGFloat;
if param < 0 || (v.x == w.x && v.y == w.y) {
int_x = v.x;
int_y = v.y;
} else if param > 1 {
int_x = w.x;
int_y = w.y;
} else {
int_x = v.x + param * wv_dx;
int_y = v.y + param * wv_dy;
}
let dx = p.x - int_x;
let dy = p.y - int_y;
return sqrt(dx * dx + dy * dy);
}
func checkIfPointIsCloseOrOnTheLine(start:CGPoint, end:CGPoint, aPoint:CGPoint, tollerance:CGFloat = 15) -> Bool{
let barHeight = self.navigationController?.navigationBar.frame.size.height;
let newStartPoint = CGPoint(x:start.x, y:start.y - barHeight!);
let newEndPoint = CGPoint(x:end.x, y:end.y - barHeight!);
let distance = distanceFromPoint(p:aPoint, v:newStartPoint, w:newEndPoint);
if distance > tollerance{
return false;
}
return true;
}

Allow PieChartView to hide value line for tiny slices in Swift

I'm building a pie chart by chart iOS framework. I'm able to hide the value and label when the the slice is tiny but I can't hide the value line for tiny slice.
If I add this code on setDataCount()
set.valueLineWidth = 0.0
It will hide all the value line. How to hide it by the size of slice?
#IBOutlet weak var myChart: PieChartView!
var valueColors = [UIColor]()
var dataEntries = [PieChartDataEntry]()
var record = [Record]()
var category = [String]()
var categoryTotal : [Double] = []
var categoryArray : [String] = []
func setDataCount() {
var totalValue = 0.0
for a in categoryTotal {
totalValue += a
}
UserDefaults.standard.set(totalValue, forKey: "totalValue")
valueAndColor()
let set = PieChartDataSet(values: dataEntries, label: nil)
set.colors = valueColors
set.valueLinePart1OffsetPercentage = 0.8
set.valueLinePart1Length = 0.2
set.valueLinePart2Length = 0.4
set.xValuePosition = .outsideSlice
set.yValuePosition = .outsideSlice
set.selectionShift = 0.0
let data = PieChartData(dataSet: set)
let Formatter:ChartFormatter = ChartFormatter()
data.setValueFormatter(Formatter)
data.setValueFont(.systemFont(ofSize: 11, weight: .light))
data.setValueTextColor(.black)
myChart.data = data
myChart.highlightValues(nil)
}
func valueAndColor(){
for i in 0..<categoryArray.count{
let dataEntry = PieChartDataEntry(value: categoryTotal[i], label: categoryArray[i % categoryArray.count])
dataEntries.append(dataEntry)
//I'm using this code to hide the label
let value = categoryTotal[i]
let total = UserDefaults.standard.double(forKey: "totalValue")
var valueToUse = value/total * 100
valueToUse = Double(round(10*valueToUse)/10)
let minNumber = 10.0
if(valueToUse < minNumber) {
dataEntries[i].label = ""
}else{
dataEntries[i].label = categoryArray[i % categoryArray.count]
}
if categoryArray[i] == "吃喝" {
valueColors.append(UIColor.yellow)
}...
}
I'm using this code to hide the value %
public class ChartFormatter: NSObject, IValueFormatter{
public func stringForValue(_ value: Double, entry: ChartDataEntry, dataSetIndex: Int, viewPortHandler: ViewPortHandler?) -> String {
let total = UserDefaults.standard.double(forKey: "totalValue")
var valueToUse = value/total * 100
valueToUse = Double(round(10*valueToUse)/10)
let minNumber = 10.0
if(valueToUse < minNumber) {
return ""
}
else {
let pFormatter = NumberFormatter()
pFormatter.numberStyle = .percent
pFormatter.maximumFractionDigits = 1
pFormatter.multiplier = 1
pFormatter.percentSymbol = " %"
let hideValue = pFormatter.string(from: NSNumber(value: value))
return String(hideValue ?? "0")
}
}
}
Inside the file PieChartRenderer change from this:
if dataSet.valueLineColor != nil
{
context.setStrokeColor(dataSet.valueLineColor!.cgColor)
context.setLineWidth(dataSet.valueLineWidth)
context.move(to: CGPoint(x: pt0.x, y: pt0.y))
context.addLine(to: CGPoint(x: pt1.x, y: pt1.y))
context.addLine(to: CGPoint(x: pt2.x, y: pt2.y))
context.drawPath(using: CGPathDrawingMode.stroke)
}
to this:
if dataSet.valueLineColor != nil
{
if(valueText == "") {
context.setStrokeColor(UIColor.clear.cgColor)
}
else {
context.setStrokeColor(dataSet.valueLineColor!.cgColor)
}
context.setLineWidth(dataSet.valueLineWidth)
context.move(to: CGPoint(x: pt0.x, y: pt0.y))
context.addLine(to: CGPoint(x: pt1.x, y: pt1.y))
context.addLine(to: CGPoint(x: pt2.x, y: pt2.y))
context.drawPath(using: CGPathDrawingMode.stroke)
}
The change basically checks if the valueText is the empty string, and if so it changes the linecolor to a clear color.

How to make sprites follow a random pattern within a circle?

I am makeing a game in which I want that the enemies move following a random pattern within a circle. I already made that the enemies spawn randomly in all the sides of the screen, but the problem is that I dont know how to make the enemies move following a random pattern within a circle just like the image.
class GameScene: SKScene, SKPhysicsContactDelegate {
var circuloPrincipal = SKSpriteNode(imageNamed: "circulo")
var enemigoTimer = NSTimer()
}
override func didMoveToView(view: SKView) {
circuloPrincipal.size = CGSize(width: 225, height: 225)
circuloPrincipal.position = CGPoint(x: frame.width / 2, y: frame.height / 2)
circuloPrincipal.color = colorAzul
circuloPrincipal.colorBlendFactor = 1.0
circuloPrincipal.name = "circuloPrincipal"
circuloPrincipal.zPosition = 1.0
self.addChild(circuloPrincipal)
override func touchesBegan(touches: Set, withEvent event: UIEvent?) {
enemigoTimer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: Selector("enemigos"), userInfo: nil, repeats: true)
}
func enemigos() {
let enemigo = SKSpriteNode(imageNamed: "enemigo")
enemigo.size = CGSize(width: 25, height: 25)
enemigo.zPosition = 2.0
enemigo.name = "enemigo"
let posisionRandom = arc4random() % 4
switch posisionRandom {
case 0:
enemigo.position.x = 0
let posisionY = arc4random_uniform(UInt32(frame.size.height))
enemigo.position.y = CGFloat(posisionY)
self.addChild(enemigo)
break
case 1:
enemigo.position.y = 0
let posisionX = arc4random_uniform(UInt32(frame.size.width))
enemigo.position.x = CGFloat(posisionX)
self.addChild(enemigo)
break
case 2:
enemigo.position.y = frame.size.height
let posisionX = arc4random_uniform(UInt32(frame.size.width))
enemigo.position.x = CGFloat(posisionX)
self.addChild(enemigo)
break
case 3:
enemigo.position.x = frame.size.width
let posisionY = arc4random_uniform(UInt32(frame.size.height))
enemigo.position.y = CGFloat(posisionY)
self.addChild(enemigo)
break
default:
break
}
enemigo.runAction(SKAction.moveTo(circuloPrincipal.position, duration: 1.4))
}
Try to add this code:
let randomY = CGFloat(Int.random(-Int(circuloPrincipal.frame.height/2)...Int(circuloPrincipal.frame.height/2)))
let randomX = CGFloat(Int.random(-Int(circuloPrincipal.frame.width/2)...Int(circuloPrincipal.frame.width/2)))
let slopeToCirculoPrincipal = (enemigo.position.y - circuloPrincipal.position.y + randomY ) / (enemigo.position.x - circuloPrincipal.position.x + randomX)
let constant = enemigo.position.y - slopeToCirculoPrincipal * enemigo.position.x
let finalX : CGFloat = enemigo.position.x < circuloPrincipal.position.x ? 1500.0 : -1500.0 // Set it to somewhere outside screen size
let finalY = constant + slopeToCirculoPrincipal * finalX
let distance = (enemigo.position.y - finalY) * (enemigo.position.y - finalY) + (enemigo.position.x - finalX) * (enemigo.position.x - finalX)
let enemigoSpeed : CGFloat = 100.0
let timeToCoverDistance = sqrt(distance) / enemigoSpeed
let moveAction = SKAction.moveTo(CGPointMake(finalX, finalY), duration: NSTimeInterval(timeToCoverDistance))
let removeAction = SKAction.runBlock { () -> Void in
enemigo.removeFromParent()
}
enemigo.runAction(SKAction.sequence([moveAction,removeAction]))
Instead of:
enemigo.runAction(SKAction.moveTo(circuloPrincipal.position, duration: 1.4))
Also you need to put this extension somewhere in your project:
extension Int
{
static func random(range: Range<Int> ) -> Int
{
var offset = 0
if range.startIndex < 0 // allow negative ranges
{
offset = abs(range.startIndex)
}
let mini = UInt32(range.startIndex + offset)
let maxi = UInt32(range.endIndex + offset)
return Int(mini + arc4random_uniform(maxi - mini)) - offset
}
}