Connect points in grid with lines - swift

I need to put line that will connect every 2 points in the grid when someone tap between those points , so they can be connected . I manage to create the point grid :
func drawPointGrid() {
let points: CGFloat = 5
let cellWidth = bounds.width / points
let cellHeight = bounds.height / points
for i in 0..<Int(points) {
for j in 0..<Int(points) {
let circleX: CGFloat = ((CGFloat(i) + 0.5) * cellWidth)
let circleY: CGFloat = ((CGFloat(j) + 0.5) * cellHeight)
let centerCirclePath = UIBezierPath(ovalIn: CGRect(x: circleX, y: circleY, width: diameter, height: diameter))
let customlayer = CAShapeLayer()
customlayer.path = centerCirclePath.cgPath
customlayer.fillColor = UIColor.black.cgColor
layer.addSublayer(customlayer)
}
}
}
This is my visual point grid :
I manage to make line on the view , but only when I click for start point and click again for end point, so the line to be created , but I need this line to be created between every 2 points on horizontal and vertical when user tap between them :
override func draw(_ rect: CGRect) {
drawPointGrid()
tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(showMoreActions))
tapGestureRecognizer.numberOfTapsRequired = 1
addGestureRecognizer(tapGestureRecognizer)
}
// draw line from point to point that are clicked
var firstPoint: CGPoint?
var secondPoint: CGPoint?
func showMoreActions(touch: UITapGestureRecognizer) {
let touchPoint = touch.location(in: self)
guard let _ = firstPoint else {
firstPoint = touchPoint
return
}
guard let _ = secondPoint else {
secondPoint = touchPoint
addLine(start: firstPoint!,end: secondPoint!)
firstPoint = nil
secondPoint = nil
return
}
}
func addLine(start: CGPoint,end:CGPoint) {
let line = CAShapeLayer()
let linePath = UIBezierPath()
linePath.move(to: start)
linePath.addLine(to: end)
line.path = linePath.cgPath
line.strokeColor = UIColor.black.cgColor
line.lineWidth = 2
line.lineJoin = kCALineJoinRound
layer.addSublayer(line)
}

I've written a function called findEndPoints that finds the CGPoint coordinates of the proper line end points given a touchPoint in the view. I did most of the work as type Double to keep from having to worry about converting between that and CGFloat.
I also moved the setup of the touchGestureRecognizer to a setup routine that is called from the inits since you only want to do that once and draw could be called more than once.
class DotsView: UIView {
let diameter = CGFloat(5)
func setup() {
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(showMoreActions))
tapGestureRecognizer.numberOfTapsRequired = 1
addGestureRecognizer(tapGestureRecognizer)
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override func draw(_ rect: CGRect) {
drawPointGrid()
}
// draw line between points
func showMoreActions(touch: UITapGestureRecognizer) {
let touchPoint = touch.location(in: self)
let (start, end) = findEndPoints(touchPt: touchPoint)
addLine(start: start, end: end)
}
func addLine(start: CGPoint,end:CGPoint) {
let line = CAShapeLayer()
let linePath = UIBezierPath()
linePath.move(to: start)
linePath.addLine(to: end)
line.path = linePath.cgPath
line.strokeColor = UIColor.black.cgColor
line.lineWidth = 2
line.lineJoin = kCALineJoinRound
layer.addSublayer(line)
}
func drawPointGrid() {
let points: CGFloat = 5
let diameter: CGFloat = 5
let cellWidth = bounds.width / points
let cellHeight = bounds.height / points
for i in 0..<Int(points) {
for j in 0..<Int(points) {
let circleX: CGFloat = ((CGFloat(i) + 0.5) * cellWidth)
let circleY: CGFloat = ((CGFloat(j) + 0.5) * cellHeight)
let centerCirclePath = UIBezierPath(ovalIn: CGRect(x: circleX, y: circleY, width: diameter, height: diameter))
let customlayer = CAShapeLayer()
customlayer.path = centerCirclePath.cgPath
customlayer.fillColor = UIColor.black.cgColor
layer.addSublayer(customlayer)
}
}
}
func findEndPoints(touchPt: CGPoint) -> (pt1: CGPoint, pt2: CGPoint) {
let points = 5.0
let cellWidth = Double(bounds.width) / points
let cellHeight = Double(bounds.height) / points
// convert touch point to grid coordinates
let gridX = Double(touchPt.x) / cellWidth - 0.5
let gridY = Double(touchPt.y) / cellHeight - 0.5
// snap to nearest point in the grid
let snapX = round(gridX)
let snapY = round(gridY)
// find distance from touch to snap point
let distX = abs(gridX - snapX)
let distY = abs(gridY - snapY)
// start second point on top of first
var secondX = snapX
var secondY = snapY
if distX < distY {
// this is a vertical line
if secondY > gridY {
secondY -= 1
} else {
secondY += 1
}
} else {
// this is a horizontal line
if secondX > gridX {
secondX -= 1
} else {
secondX += 1
}
}
let halfdot = Double(diameter) / 2
// convert line points to view coordinates
let pt1 = CGPoint(x: (snapX + 0.5) * cellWidth + halfdot, y: (snapY + 0.5) * cellHeight + halfdot)
let pt2 = CGPoint(x: (secondX + 0.5) * cellWidth + halfdot, y: (secondY + 0.5) * cellHeight + halfdot)
return (pt1, pt2)
}
}

Related

Cropping is not working perfectly as per the frame drawn

I am trying to crop a selected portion of NSImage which is fitted as per ProportionallyUpOrDown(AspectFill) Mode.
I am drawing a frame using mouse dragged event like this:
class CropImageView: NSImageView {
var startPoint: NSPoint!
var shapeLayer: CAShapeLayer!
var flagCheck = false
var finalPoint: NSPoint!
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
}
override var image: NSImage? {
set {
self.layer = CALayer()
self.layer?.contentsGravity = kCAGravityResizeAspectFill
self.layer?.contents = newValue
self.wantsLayer = true
super.image = newValue
}
get {
return super.image
}
}
override func mouseDown(with event: NSEvent) {
self.startPoint = self.convert(event.locationInWindow, from: nil)
if self.shapeLayer != nil {
self.shapeLayer.removeFromSuperlayer()
self.shapeLayer = nil
}
self.flagCheck = true
var pixelColor: NSColor = NSReadPixel(startPoint) ?? NSColor()
shapeLayer = CAShapeLayer()
shapeLayer.lineWidth = 1.0
shapeLayer.fillColor = NSColor.clear.cgColor
if pixelColor == NSColor.black {
pixelColor = NSColor.color_white
} else {
pixelColor = NSColor.black
}
shapeLayer.strokeColor = pixelColor.cgColor
shapeLayer.lineDashPattern = [1]
self.layer?.addSublayer(shapeLayer)
var dashAnimation = CABasicAnimation()
dashAnimation = CABasicAnimation(keyPath: "lineDashPhase")
dashAnimation.duration = 0.75
dashAnimation.fromValue = 0.0
dashAnimation.toValue = 15.0
dashAnimation.repeatCount = 0.0
shapeLayer.add(dashAnimation, forKey: "linePhase")
}
override func mouseDragged(with event: NSEvent) {
let point: NSPoint = self.convert(event.locationInWindow, from: nil)
var newPoint: CGPoint = self.startPoint
let xDiff = point.x - self.startPoint.x
let yDiff = point.y - self.startPoint.y
let dist = min(abs(xDiff), abs(yDiff))
newPoint.x += xDiff > 0 ? dist : -dist
newPoint.y += yDiff > 0 ? dist : -dist
let path = CGMutablePath()
path.move(to: self.startPoint)
path.addLine(to: NSPoint(x: self.startPoint.x, y: newPoint.y))
path.addLine(to: newPoint)
path.addLine(to: NSPoint(x: newPoint.x, y: self.startPoint.y))
path.closeSubpath()
self.shapeLayer.path = path
}
override func mouseUp(with event: NSEvent) {
self.finalPoint = self.convert(event.locationInWindow, from: nil)
}
}
and selected this area as shown in picture using black dotted line:
My Cropping Code logic is this:
// resize Image Methods
extension CropProfileView {
func resizeImage(image: NSImage) -> Data {
var scalingFactor: CGFloat = 0.0
if image.size.width >= image.size.height {
scalingFactor = image.size.width/cropImgView.size.width
} else {
scalingFactor = image.size.height/cropImgView.size.height
}
let width = (self.cropImgView.finalPoint.x - self.cropImgView.startPoint.x) * scalingFactor
let height = (self.cropImgView.startPoint.y - self.cropImgView.finalPoint.y) * scalingFactor
let xPos = ((image.size.width/2) - (cropImgView.bounds.midX - self.cropImgView.startPoint.x) * scalingFactor)
let yPos = ((image.size.height/2) - (cropImgView.bounds.midY - (cropImgView.size.height - self.cropImgView.startPoint.y)) * scalingFactor)
var croppedRect: NSRect = NSRect(x: xPos, y: yPos, width: width, height: height)
let imageRef = image.cgImage(forProposedRect: &croppedRect, context: nil, hints: nil)
guard let croppedImage = imageRef?.cropping(to: croppedRect) else {return Data()}
let imageWithNewSize = NSImage(cgImage: croppedImage, size: NSSize(width: width, height: height))
guard let data = imageWithNewSize.tiffRepresentation,
let rep = NSBitmapImageRep(data: data),
let imgData = rep.representation(using: .png, properties: [.compressionFactor: NSNumber(floatLiteral: 0.25)]) else {
return imageWithNewSize.tiffRepresentation ?? Data()
}
return imgData
}
}
With this cropping logic i am getting this output:
I think as image is AspectFill thats why its not getting cropped in perfect size as per selected frame. Here if you look at output: xpositon & width & heights are not perfect. Or probably i am not calculating these co-ordinates properly. Let me know the faults probably i am calculating someting wrong.
Note: the CropImageView class in the question is a subclass of NSImageView but the view is layer-hosting and the image is drawn by the layer, not by NSImageView. imageScaling is not used.
When deciding which scaling factor to use you have to take the size of the image view into account. If the image size is width:120, height:100 and the image view size is width:120, height 80 then image.size.width >= image.size.height is true and image.size.width/cropImgView.size.width is 1 but the image is scaled because image.size.height/cropImgView.size.height is 1.25. Calculate the horizontal and vertical scaling factors and use the largest.
See How to crop a UIImageView to a new UIImage in 'aspect fill' mode?
Here's the calculation of croppedRect assuming cropImgView.size returns self.layer!.bounds.size.
var scalingWidthFactor: CGFloat = image.size.width/cropImgView.size.width
var scalingHeightFactor: CGFloat = image.size.height/cropImgView.size.height
var xOffset: CGFloat = 0
var yOffset: CGFloat = 0
switch cropImgView.layer?.contentsGravity {
case CALayerContentsGravity.resize: break
case CALayerContentsGravity.resizeAspect:
if scalingWidthFactor > scalingHeightFactor {
scalingHeightFactor = scalingWidthFactor
yOffset = (cropImgView.size.height - (image.size.height / scalingHeightFactor)) / 2
}
else {
scalingWidthFactor = scalingHeightFactor
xOffset = (cropImgView.size.width - (image.size.width / scalingWidthFactor)) / 2
}
case CALayerContentsGravity.resizeAspectFill:
if scalingWidthFactor < scalingHeightFactor {
scalingHeightFactor = scalingWidthFactor
yOffset = (cropImgView.size.height - (image.size.height / scalingHeightFactor)) / 2
}
else {
scalingWidthFactor = scalingHeightFactor
xOffset = (cropImgView.size.width - (image.size.width / scalingWidthFactor)) / 2
}
default:
print("contentsGravity \(String(describing: cropImgView.layer?.contentsGravity)) is not supported")
return nil
}
let width = (self.cropImgView.finalPoint.x - self.cropImgView.startPoint.x) * scalingWidthFactor
let height = (self.cropImgView.startPoint.y - self.cropImgView.finalPoint.y) * scalingHeightFactor
let xPos = (self.cropImgView.startPoint.x - xOffset) * scalingWidthFactor
let yPos = (cropImgView.size.height - self.cropImgView.startPoint.y - yOffset) * scalingHeightFactor
var croppedRect: NSRect = NSRect(x: xPos, y: yPos, width: width, height: height)
Bugfix: cropImgView.finalPoint should be the corner of the selection, not the location of mouseUp. In CropImageView set self.finalPoint = newPoint in mouseDragged instead of mouseUp.

How to use the Zposition of UIBezierPath() and SKNode?

I have a UIView where i draw lines with UIBezierPath() and where i have SKSHapeNode child. Sometimes, the drawing is superimposed with the nodes. When it is the case, i want the node to be upside of the drawing. But even wehn the nodes have a bigger Zpos, the drawing is upside nodes.
I use this script when i want to draw a line :
private func addLine(fromPoint start: CGPoint, toPoint end:CGPoint) {
let line = CAShapeLayer()
let linePath = UIBezierPath()
linePath.move(to: start)
linePath.addLine(to: end)
line.zPosition = 80
line.path = linePath.cgPath
line.strokeColor = UIColor.black.cgColor
line.lineWidth = 5.0
line.lineJoin = CAShapeLayerLineJoin.round
self.view!.layer.addSublayer(line)
}
And i use this script for the SKSHapeNodes :
private func drawBase(map : Int) {
for i in 0...maps.xMaps[map].count - 1 {
let team = maps.mapTeam[map][i]
let weight = CGFloat(game!.baseWeight[i])
let base = SKShapeNode(rectOf: CGSize(width: weight, height: weight))
base.zPosition = 90
base.position = CGPoint(x: maps.xMaps[map][i], y: maps.yMaps[map][i])
if team == 0 {
base.fillColor = .blue
} else if team == 1 {
base.fillColor = .red
} else if team == 2 {
base.fillColor = .green
} else if team == 3 {
base.fillColor = .purple
}
mapEntity.append(base)
self.addChild(base)
}
}
I call the function here :
func drawMap(map : Int){
drawRoad(map: map)
drawBase(map: map)
}
DrawRoad is the function that draw lines :
private func drawRoad(map : Int) {
for i in 0...maps.xRoad[map].count - 1 {
let start = CGPoint(x: maps.xRoad[map][i][0], y: self.frame.height - maps.yRoad[map][i][0])
let end = CGPoint(x: maps.xRoad[map][i][1], y: self.frame.height - maps.yRoad[map][i][1])
addLine(fromPoint: start, toPoint: end)
}
}
As you can see i draw the line before adding the SKShapeNode but it do not work...

Leaving equal width gap spacing before and between menu buttons

I have created a scrolling menu using the code below. I am trying to create equal row gaps (width spacing) between each of the menu sprite buttons. Currently, I've been able to leave equal width spacing at the left and right ends but not in between sprite buttons. Please see the relevant code below:
class LevelScene: SKScene {
let levelButtonSize = SKSpriteNode(imageNamed: "b1").size
let levelButton1: SKSpriteNode = SKSpriteNode(imageNamed: "b1")
let levelButton2: SKSpriteNode = SKSpriteNode(imageNamed: "b2")
let levelButton3: SKSpriteNode = SKSpriteNode(imageNamed: "b3")
let levelButton4: SKSpriteNode = SKSpriteNode(imageNamed: "b4")
let levelButton5: SKSpriteNode = SKSpriteNode(imageNamed: "b5")
let levelButton6: SKSpriteNode = SKSpriteNode(imageNamed: "b6")
let levelButton7: SKSpriteNode = SKSpriteNode(imageNamed: "b7")
let levelButton8: SKSpriteNode = SKSpriteNode(imageNamed: "b8")
let levelButton9: SKSpriteNode = SKSpriteNode(imageNamed: "b9")
let levelButton10: SKSpriteNode = SKSpriteNode(imageNamed: "b10")
let levelButton11: SKSpriteNode = SKSpriteNode(imageNamed: "b11")
let levelButton12: SKSpriteNode = SKSpriteNode(imageNamed: "b12")
let levelButton13: SKSpriteNode = SKSpriteNode(imageNamed: "b13")
let levelButton14: SKSpriteNode = SKSpriteNode(imageNamed: "b14")
let levelButton15: SKSpriteNode = SKSpriteNode(imageNamed: "b15")
let levelButton16: SKSpriteNode = SKSpriteNode(imageNamed: "b16")
let levelButton17: SKSpriteNode = SKSpriteNode(imageNamed: "b17")
let levelButton18: SKSpriteNode = SKSpriteNode(imageNamed: "b18")
private var scrollCell = SKSpriteNode()
private var moveAmtX: CGFloat = 0
private var moveAmtY: CGFloat = 0
private let minimum_detect_distance: CGFloat = 30
private var initialPosition: CGPoint = CGPoint.zero
private var initialTouch: CGPoint = CGPoint.zero
private var resettingSlider = false
override init(size: CGSize){
super.init(size: size)
createMenu()
}
func createMenu() {
let buttons = [levelButton1, levelButton2, levelButton3, levelButton4, levelButton5, levelButton6, levelButton7, levelButton8, levelButton9, levelButton10, levelButton11, levelButton12, levelButton13, levelButton14, levelButton15, levelButton16, levelButton17, levelButton18]
for i in 1..<buttons.count {
buttons[i-1].name = "level\(i)"
}
let padding: CGFloat = 50
let numberOfRows = CGFloat(buttons.count / 3)
scrollCell = SKSpriteNode(color: .blue, size: CGSize(width: self.size.width, height: levelButtonSize.height * numberOfRows + padding * numberOfRows))
scrollCell.position = CGPoint(x: 0 - self.size.width / 2, y: 0 - (scrollCell.size.height - self.size.height / 2))
scrollCell.anchorPoint = CGPoint.zero
scrollCell.zPosition = 0
self.addChild(scrollCell)
// let backgroundImage = SKSpriteNode(imageNamed: "bg")
// backgroundImage.position = CGPoint(x: self.frame.midX, y: self.frame.midY)
// self.addChild(backgroundImage)
let totalMarginX = self.frame.width - 3*levelButtonSize.width
let marginX = totalMarginX/4
let column1PosX = marginX + levelButtonSize.width/2
let column2PosX = 2*marginX + 3*levelButtonSize.width/2
let column3PosX = 3*marginX + 5*levelButtonSize.width/2
print("levelButtonSize.width is \(levelButtonSize.width)")
print("self.frame.width is \(self.frame.width)")
print("marginX is \(marginX)")
print("column1PosX is \(column1PosX)")
print("column2PosX is \(column2PosX)")
print("column3PosX is \(column3PosX)")
var colCount = 0
var rowCount = 0
for button in buttons {
var posX: CGFloat = column2PosX
if colCount == 0 {
posX = column1PosX
}
if colCount == 1 {
posX = column2PosX
}
else if colCount == 2 {
posX = column3PosX
colCount = -1
}
let indexOffset = CGFloat(rowCount) * (levelButtonSize.height + padding)
let posY = scrollCell.size.height - levelButtonSize.height / 2 - (indexOffset + padding / 2)
button.position = CGPoint(x: posX, y: posY)
//button.setScale(0.5)
button.zPosition = 10
scrollCell.addChild(button)
if colCount == -1 {
rowCount += 1
}
colCount += 1
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first as UITouch! {
self.scrollCell.removeAllActions()
initialTouch = touch.location(in: self.scene!.view)
moveAmtY = 0
initialPosition = self.scrollCell.position
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first as UITouch! {
let movingPoint: CGPoint = touch.location(in: self.scene!.view)
moveAmtX = movingPoint.x - initialTouch.x
let topPos: CGFloat = scrollCell.size.height - self.size.height / 2
let bottomPos = 0 - (self.size.height / 2)
if (initialPosition.y - (movingPoint.y - initialTouch.y)) < -topPos {
print("stop on top")
moveAmtY = 0
scrollCell.position.y = -topPos
}
else if (initialPosition.y - (movingPoint.y - initialTouch.y)) > bottomPos {
print("stop on bottom")
moveAmtY = 0
scrollCell.position.y = bottomPos
}
else {
moveAmtY = movingPoint.y - initialTouch.y
scrollCell.position = CGPoint(x: initialPosition.x, y: initialPosition.y - moveAmtY)
}
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
}
func checkForResettingSlider() {
let topPos: CGFloat = scrollCell.size.height - self.size.height / 2
let bottomPos = 0 - (self.size.height / 2)
if scrollCell.position.y > bottomPos {
let move = SKAction.moveTo(y: bottomPos, duration: 0.3)
move.timingMode = .easeOut
scrollCell.run(move)
}
if scrollCell.position.y < -topPos {
let move = SKAction.moveTo(y: -topPos, duration: 0.3)
move.timingMode = .easeOut
scrollCell.run(move)
}
}
func yMoveActions(moveTo: CGFloat) {
let move = SKAction.moveBy(x: 0, y: (moveTo * 1.5), duration: 0.3)
move.timingMode = .easeOut
self.scrollCell.run(move, completion: { self.checkForResettingSlider() })
}
Please note that I set the scene in the following way:
let levelScene = LevelScene(size: CGSize(width:480, height:640))
levelScene.anchorPoint = CGPoint(x: 0.5, y: 0.5)
levelScene.scaleMode = .aspectFill
skView?.presentScene(levelScene)
EDIT
The image below shows a portion of my level menu which has more space between the level buttons as compared to the sides. I want to get the same width gaps between buttons and also at the sides.
I would suggest:
let scaledWidth = levelButtonSize.width/2;
let totalMarginX = self.frame.width - 3*scaledWidth
let marginX = totalMarginX/4
let column1PosX = marginX + scaledWidth/2
let column2PosX = 2*marginX + 3*scaledWidth/2
let column3PosX = 3*marginX + 5*scaledWidth/2

Something's wrong with my scheduledTimer on SpriteKit

I'm experimenting a few things with Swift and SpriteKit.
I have 4 images of coins. (coin1,coin2, ...). I want to spawn a random coin at a random position on the screen and let it fade out. I want to repeat this action every 3 seconds. This is the code and it worked fine.
class GameScene: SKScene {
// creating a playable area
let gameArea: CGRect
override init(size: CGSize) {
let maxAspectRatio: CGFloat = 16.0/9.0
let playableWidth = size.height / maxAspectRatio
let gameAreaMargin = (size.width - playableWidth)/2
gameArea = CGRect(x: gameAreaMargin, y: 270, width: playableWidth, height: size.height - 270)
super.init(size: size)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func random() -> CGFloat {
return CGFloat(Float(arc4random()) / 0xFFFFFFFF)
}
func random(min: CGFloat, max: CGFloat) -> CGFloat {
return random() * (max-min) + min
}
func spawnAndFadeCoins() -> SKSpriteNode{
let randNum = arc4random()%4 + 1
let coin = SKSpriteNode(imageNamed: "coin\(randNum)")
if randNum == 4 {
coin.zPosition = 10
}
else {
coin.zPosition = 5
}
coin.name = "coin\(randNum)"
let randomX = random(min: gameArea.minX + coin.size.width/2,
max: gameArea.maxX - coin.size.width/2)
let randomY = random(min: gameArea.minY + coin.size.height/2,
max: gameArea.maxY - coin.size.height/2)
coin.position = CGPoint(x: randomX, y: randomY)
let disappear = SKAction.fadeOut(withDuration: 1.0)
coin.run(SKAction.repeatForever(disappear))
self.addChild(coin)
return(coin)
}
override func didMove(to view: SKView) {
let background = SKSpriteNode(imageNamed:"bg")
background.size = self.size
background.position = CGPoint(x:self.frame.size.width/2, y: self.frame.size.height/2)
background.zPosition = 0
self.addChild(background)
var _ = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(GameScene.spawnAndFadeCoins), userInfo: nil, repeats: true)
}
}
However, when I add a label to each coin specifying its name, something weird happens: After every 3 seconds, 3 coins appear simultaneously on the screen. The label is placed on 1 of those 3 coins, and it doesn't even say the coin's name correctly. This is the new code:
class GameScene: SKScene {
// creating a playable area
let gameArea: CGRect
override init(size: CGSize) {
let maxAspectRatio: CGFloat = 16.0/9.0
let playableWidth = size.height / maxAspectRatio
let gameAreaMargin = (size.width - playableWidth)/2
gameArea = CGRect(x: gameAreaMargin, y: 270, width: playableWidth, height: size.height - 270)
super.init(size: size)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func random() -> CGFloat {
return CGFloat(Float(arc4random()) / 0xFFFFFFFF)
}
func random(min: CGFloat, max: CGFloat) -> CGFloat {
return random() * (max-min) + min
}
func spawnAndFadeCoins() -> SKSpriteNode{
let randNum = arc4random()%4 + 1
let coin = SKSpriteNode(imageNamed: "coin\(randNum)")
if randNum == 4 {
coin.zPosition = 10
}
else {
coin.zPosition = 5
}
coin.name = "coin\(randNum)"
let randomX = random(min: gameArea.minX + coin.size.width/2,
max: gameArea.maxX - coin.size.width/2)
let randomY = random(min: gameArea.minY + coin.size.height/2,
max: gameArea.maxY - coin.size.height/2)
coin.position = CGPoint(x: randomX, y: randomY)
let disappear = SKAction.fadeOut(withDuration: 1.0)
coin.run(SKAction.repeatForever(disappear))
self.addChild(coin)
return(coin)
}
func spawnAndFadeLabels() -> SKLabelNode{
let label = SKLabelNode()
label.text = "\(spawnAndFadeCoins().name)"
label.zPosition = 15
label.color = SKColor.white()
label.fontSize = 60
label.position = spawnAndFadeCoins().position
let disappear2 = SKAction.fadeOut(withDuration: 1.0)
label.run(SKAction.repeatForever(disappear2))
self.addChild(label)
return(label)
}
override func didMove(to view: SKView) {
let background = SKSpriteNode(imageNamed:"bg")
background.size = self.size
background.position = CGPoint(x:self.frame.size.width/2, y: self.frame.size.height/2)
background.zPosition = 0
self.addChild(background)
var _ = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(GameScene.spawnAndFadeCoins), userInfo: nil, repeats: true)
var _ = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(GameScene.spawnAndFadeLabels), userInfo: nil, repeats: true)
}
}
Can you help me solve this mystery? Thanks in advance.
The problem is that you called spawnAndFadeCoins two more times in spawnAndFadeLabels:
func spawnAndFadeLabels() -> SKLabelNode{
let label = SKLabelNode()
label.text = "\(spawnAndFadeCoins().name)" <-- here!
label.zPosition = 15
label.color = SKColor.white()
label.fontSize = 60
label.position = spawnAndFadeCoins().position <-- and here!
let disappear2 = SKAction.fadeOut(withDuration: 1.0)
label.run(SKAction.repeatForever(disappear2))
self.addChild(label)
return(label)
}
I think one thing you can do to solve it is this:
Have only one timer:
runAction(SKAction.repeatForever(SKAction.sequence([SKAction.wait(forDuration: 3), SKAction.run(spawnAndFadeCoins)])))
I used SKActions here because it is not recommended to use Timer in spritekit.
Now only spawnAndFadeCoins will be called once every three seconds. Then, change spawnAndFadeLabels to:
func spawnAndFadeLabels(of node: SKSpriteNode) -> SKLabelNode{
let label = SKLabelNode()
label.text = "\(node.name)"
label.zPosition = 15
label.color = SKColor.white()
label.fontSize = 60
label.position = node.position
let disappear2 = SKAction.fadeOut(withDuration: 1.0)
label.run(SKAction.repeatForever(disappear2))
self.addChild(label)
return(label)
}
Change spawnAndFadeCoins to:
func spawnAndFadeCoins() -> SKSpriteNode{
let randNum = arc4random()%4 + 1
let coin = SKSpriteNode(imageNamed: "coin\(randNum)")
if randNum == 4 {
coin.zPosition = 10
}
else {
coin.zPosition = 5
}
coin.name = "coin\(randNum)"
let randomX = random(min: gameArea.minX + coin.size.width/2,
max: gameArea.maxX - coin.size.width/2)
let randomY = random(min: gameArea.minY + coin.size.height/2,
max: gameArea.maxY - coin.size.height/2)
coin.position = CGPoint(x: randomX, y: randomY)
let disappear = SKAction.fadeOut(withDuration: 1.0)
coin.run(SKAction.repeatForever(disappear))
self.addChild(coin)
spawnAndFadeLabels(of: coin) <-- This line is added!
return(coin)
}
I think this is want you want.

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
}
}