Repeating a Background Image in Swift - xcode

Im using swift programming language in xcode and in spritekit. I want to get my background image to scroll forever. I have this code so far but when I run it in the simulator it goes through only one time and goes back to the grey background. How do I get it so that the background repeats forever. I already got the background to move its just that I want it to repeat forever.
class GameScene: SKScene, SKPhysicsContactDelegate {
var background = SKSpriteNode()
// Background
background = SKSpriteNode(imageNamed: "background")
background.position = CGPointMake(self.size.width/2, self.size.height/2)
addChild(background)
// Repeat Background Image Forever
moveForeverAction()
}
//loop background image infinitely
func moveForeverAction() {
let moveNode = SKAction.moveByX(0, y: background.size.height * 2.0 , duration: NSTimeInterval(0.01 * background.size.height * 2.0))
let resetPosition = SKAction.moveByX(0, y: background.size.height * 2.0, duration: 0)
let moveNodeForever = SKAction.repeatActionForever(SKAction.sequence([moveNode, resetPosition]))
background.runAction(moveNodeForever)
}

It's because you're adding the same background.
add another declaration of bacground in the loop :
for var i:CGFloat=0; i < 3; ++i {
**background = SKSpriteNode(imageNamed: "background")**
background.position = CGPointMake(background.size.width / 2, i * background.size.height )
background.runAction(moveNodeForever)
}

You've to runAction() 3 times. For example :
for var i:CGFloat=0; i < 3; ++i {
background.position = CGPointMake(background.size.width / 2, i * background.size.height )
background.runAction(moveNodeForever)
}

Related

How to show WorldOrigin axis in SceneKit scene for macOS?

I am building a macOS SwiftUI app. I want to show the world axis such that the user is aware of the orientation of objects. I've looked at the documentation, but the showWorldOrigin debug setting is not available on macOS. Is there an alternative way to show the world axis that I am missing?
While I've found external libraries that create a world axis and add nodes to the scene, I was hoping there was a built-in method to simplify the task and reduce any error.
You can create your own sample of procedural world axis for macOS 3D app.
SwiftUI mac version
import SwiftUI
import SceneKit
struct ContentView : View {
#State private var scene = SCNScene()
#State private var axis = SCNNode()
var options: SceneView.Options = [.allowsCameraControl]
var body: some View {
ZStack {
SceneView(scene: scene, options: options).ignoresSafeArea()
let _ = scene.background.contents = NSColor.black
let _ = createWorldAxis()
let _ = axis.opacity = 0.1 // you can hide world axis
}
}
func createWorldAxis() {
let colors: [NSColor] = [.systemRed, .systemGreen, .systemBlue]
for index in 0...2 {
let box = SCNBox(width: 0.200, height: 0.005,
length: 0.005, chamferRadius: 0.001)
let material = SCNMaterial()
material.lightingModel = .constant
material.diffuse.contents = colors[index]
box.materials[0] = material
let node = SCNNode(geometry: box)
switch index {
case 0:
node.position.x += 0.1
case 1:
node.eulerAngles = SCNVector3(0, 0, Float.pi/2)
node.position.y += 0.1
case 2:
node.eulerAngles = SCNVector3(0, -Float.pi/2, 0)
node.position.z += 0.1
default: break
}
axis.addChildNode(node)
axis.scale = SCNVector3(1.5, 1.5, 1.5)
scene.rootNode.addChildNode(axis)
}
print(axis.position)
}
}
Cocoa version
import Cocoa
import SceneKit
class ViewController : NSViewController {
var axis = SCNNode()
var sceneView = SCNView()
override func viewDidLoad() {
super.viewDidLoad()
sceneView = self.view as! SCNView
sceneView.scene = SCNScene()
sceneView.allowsCameraControl = true
sceneView.backgroundColor = .black
self.createWorldAxis()
axis.opacity = 0.1 // you can hide world axis
}
func createWorldAxis() {
let colors: [NSColor] = [.systemRed, .systemGreen, .systemBlue]
for index in 0...2 {
let box = SCNBox(width: 0.200, height: 0.005,
length: 0.005, chamferRadius: 0.001)
let material = SCNMaterial()
material.lightingModel = .constant
material.diffuse.contents = colors[index]
box.materials[0] = material
let node = SCNNode(geometry: box)
if index == 0 {
node.position.x += 0.1
} else if index == 1 {
node.eulerAngles = SCNVector3(0, 0, Float.pi/2)
node.position.y += 0.1
} else if index == 2 {
node.eulerAngles = SCNVector3(0, -Float.pi/2, 0)
node.position.z += 0.1
}
axis.addChildNode(node)
axis.scale = SCNVector3(1.5, 1.5, 1.5)
sceneView.scene?.rootNode.addChildNode(axis)
}
print(axis.position)
}
}
Posting this answer, as per OP comments...
Apple's docs list the following SCNDebugOptions:
.showPhysicsShapes
.showBoundingBoxes
.showLightInfluences
.showLightExtents
.showPhysicsFields
.showWireframe
.renderAsWireframe
.showSkeletons
.showCreases
.showConstraints
.showCameras
.showFeaturePoints
.showWorldOrigin
Curiously, the last two - .showFeaturePoints and .showWorldOrigin - are not defined in SceneKit. And the discussion notes refer only to ARKit, where they are defined.
The docs for SCNDebugOptions state that these are bit mask patterns ... and if we print them out, we get:
showPhysicsShapes: SCNDebugOptions(rawValue: 1)
showBoundingBoxes: SCNDebugOptions(rawValue: 2)
showLightInfluences: SCNDebugOptions(rawValue: 4)
showLightExtents: SCNDebugOptions(rawValue: 8)
showPhysicsFields: SCNDebugOptions(rawValue: 16)
showWireframe: SCNDebugOptions(rawValue: 32)
renderAsWireframe: SCNDebugOptions(rawValue: 64)
showSkeletons: SCNDebugOptions(rawValue: 128)
showCreases: SCNDebugOptions(rawValue: 256)
showConstraints: SCNDebugOptions(rawValue: 512)
showCameras: SCNDebugOptions(rawValue: 1024)
So... we try this to get "the next one in order" (expecting it to equate to .showFeaturePoints):
sceneView.debugOptions = SCNDebugOptions(rawValue: 2048)
Turns out, that gives us RGB axis indicators ... the .showWorldOrigin.
For a simple scene with an extruded bezier path (a cube), using these options:
sceneView.debugOptions = [.renderAsWireframe, SCNDebugOptions(rawValue: 2048)]
we get this output:
Trying one further, thinking maybe we get .showFeaturePoints:
sceneView.debugOptions = SCNDebugOptions(rawValue: 4096)
doesn't seem to do anything - at least, I don't see any visual change in my simple Scene.
I found what i wanted using the UI. First, ensure you enable controls for your scene:
myscene.showsStatistics = true
Then, click the configuration button on the bottom of your screen.
In the options dropdown select World Origin.
I am puzzled why all debug options can be invoked programmatically except the World Origin. None the less, that allows you to see axis.

How to Animate a UIImage out of the Screen in Swift

i have searched around the web but nothing could answer my question.
I am trying to animate an UIImageview out of the Screen, set the alpha of it to 0, reset its position and reset the alpha to 1 again.
I can't seem to get the right position where to animate the Image to.
I have set up a gesturerecognizer to drag the image around and when the center of the image is above a certain point, i want to animate it out of screen.
This is the Regocnizercode :
#objc func imageDragged(gestureRecognizer: UIPanGestureRecognizer){
//Current Point where the label is dragged
let draggedLabelPoint = gestureRecognizer.translation(in: view)
//Updating the center of the label : viewcenter +/- currentpoint
matchImageView.center = CGPoint(x: view.bounds.width/2 + draggedLabelPoint.x, y: view.bounds.height/2 + draggedLabelPoint.y)
let xFromCenter = view.bounds.width/2 - matchImageView.center.x
var rotation = CGAffineTransform(rotationAngle: xFromCenter / -500)
let scale = min(100/abs(xFromCenter),1)
var scaledAndRotated = rotation.scaledBy(x: scale, y: scale)
//Transforming the Item respective to the distance from center
matchImageView.transform = scaledAndRotated
if gestureRecognizer.state == .ended {
if matchImageView.center.x < (view.bounds.width/2 - 100) {
animateImageToSide(target: CGPoint(x: view.bounds.width - 200, y: matchImageView.center.y))
matchImageView.alpha = 0
}
if matchImageView.center.x > (view.bounds.width/2 + 100) {
animateImageToSide(target: CGPoint(x: view.bounds.width + 200, y: matchImageView.center.y))
matchImageView.alpha = 0
}
//Reset the scaling variables and recentering the Item after swipe
rotation = CGAffineTransform(rotationAngle: 0)
scaledAndRotated = rotation.scaledBy(x: 1, y: 1)
matchImageView.transform = scaledAndRotated
matchImageView.center = CGPoint(x: view.bounds.width/2, y: view.bounds.height/2)
}
}
I am sorry if the resetting part is irrelevant for you, but im not sure if this could cause this behavior.
And this is my current Animationmethod :
func animateImageToSide(target:CGPoint){
UIImageView.animate(withDuration: 0.5, delay: 0, options: .curveLinear, animations: {self.matchImageView.center = target}) { (success: Bool) in
self.updateImage()
self.fadeInImage()//This is where i set the alpha back to 1
}
}
I am not sure if a CGPoint is what i need to use.
The current behavoir of the image is very weird. Most of the time it snaps to a specific place, regardless of the targetposition. Maybe my attempt on this is entirely wrong.
Thanks for your help !

Getting Pixel Color from an Image using CGPoint in Swift 3

I am try this PixelExtractor class in Swift 3, get a error;
Cannot invoke initializer for type 'UnsafePointer' with an argument list of type '(UnsafeMutableRawPointer?)'
class PixelExtractor: NSObject {
let image: CGImage
let context: CGContextRef?
var width: Int {
get {
return CGImageGetWidth(image)
}
}
var height: Int {
get {
return CGImageGetHeight(image)
}
}
init(img: CGImage) {
image = img
context = PixelExtractor.createBitmapContext(img)
}
class func createBitmapContext(img: CGImage) -> CGContextRef {
// Get image width, height
let pixelsWide = CGImageGetWidth(img)
let pixelsHigh = CGImageGetHeight(img)
let bitmapBytesPerRow = pixelsWide * 4
let bitmapByteCount = bitmapBytesPerRow * Int(pixelsHigh)
// Use the generic RGB color space.
let colorSpace = CGColorSpaceCreateDeviceRGB()
// Allocate memory for image data. This is the destination in memory
// where any drawing to the bitmap context will be rendered.
let bitmapData = malloc(bitmapByteCount)
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedFirst.rawValue)
let size = CGSizeMake(CGFloat(pixelsWide), CGFloat(pixelsHigh))
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
// create bitmap
let context = CGBitmapContextCreate(bitmapData, pixelsWide, pixelsHigh, 8,
bitmapBytesPerRow, colorSpace, bitmapInfo.rawValue)
// draw the image onto the context
let rect = CGRect(x: 0, y: 0, width: pixelsWide, height: pixelsHigh)
CGContextDrawImage(context, rect, img)
return context!
}
func colorAt(x x: Int, y: Int)->UIColor {
assert(0<=x && x<width)
assert(0<=y && y<height)
let uncastedData = CGBitmapContextGetData(context)
let data = UnsafePointer<UInt8>(uncastedData)
let offset = 4 * (y * width + x)
let alpha: UInt8 = data[offset]
let red: UInt8 = data[offset+1]
let green: UInt8 = data[offset+2]
let blue: UInt8 = data[offset+3]
let color = UIColor(red: CGFloat(red)/255.0, green: CGFloat(green)/255.0, blue: CGFloat(blue)/255.0, alpha: CGFloat(alpha)/255.0)
return color
}
}
Fix this error.
let data = UnsafePointer<UInt8>(uncastedData)
->
let data = UnsafeRawPointer(uncastedData)
Get other error; 'Type 'UnsafeRawPointer?' has no subscript members'
How to modify this error?
You can write something like this when you have an UnsafeRawPointer in your data:
let alpha = data.load(fromByteOffset: offset, as: UInt8.self)
let red = data.load(fromByteOffset: offset+1, as: UInt8.self)
let green = data.load(fromByteOffset: offset+2, as: UInt8.self)
let blue = data.load(fromByteOffset: offset+3, as: UInt8.self)
Or else, you can get UnsafeMutablePointer<UInt8> from your uncastedData (assuming it's an UnsafeMutableRawPointer):
let data = uncastedData.assumingMemoryBound(to: UInt8.self)
SWIFT 3 (updated March 2017) Xcode 8 / IOS 10
Important: note that return value corresponds to red: b, green:r and blue: r as in the data they are stored backwards
First, create the extension (you can copy&paste somewhere in your
code)
extension UIImage {
func getPixelColor(pos: CGPoint) -> UIColor {
if let pixelData = self.cgImage?.dataProvider?.data {
let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)
let pixelInfo: Int = ((Int(self.size.width) * Int(pos.y)) + Int(pos.x)) * 4
let r = CGFloat(data[pixelInfo+0]) / CGFloat(255.0)
let g = CGFloat(data[pixelInfo+1]) / CGFloat(255.0)
let b = CGFloat(data[pixelInfo+2]) / CGFloat(255.0)
let a = CGFloat(data[pixelInfo+3]) / CGFloat(255.0)
return UIColor(red: b, green: g, blue: r, alpha: a)
} else {
//IF something is wrong I returned WHITE, but change as needed
return UIColor.white
}
}
}
Then just call it as:
let colorAtPixel : UIColor = (theView.image?.getPixelColor(pos: CGPoint(x: 2, y: 2)))!
Although the code returns de exact color, it seems that is not returning the correct one for different CGPoints.
Might it be because of the screen resolution? (x1,x2,x3)?
It would be great if someone can add some light to the mystery...
Swift-3 (IOS 10.3)
extension UIImage {
func getPixelColor(atLocation location: CGPoint, withFrameSize size: CGSize) -> UIColor {
let x: CGFloat = (self.size.width) * location.x / size.width
let y: CGFloat = (self.size.height) * location.y / size.height
let pixelPoint: CGPoint = CGPoint(x: x, y: y)
let pixelData = self.cgImage!.dataProvider!.data
let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)
let pixelIndex: Int = ((Int(self.size.width) * Int(pixelPoint.y)) + Int(pixelPoint.x)) * 4
let r = CGFloat(data[pixelIndex]) / CGFloat(255.0)
let g = CGFloat(data[pixelIndex+1]) / CGFloat(255.0)
let b = CGFloat(data[pixelIndex+2]) / CGFloat(255.0)
let a = CGFloat(data[pixelIndex+3]) / CGFloat(255.0)
return UIColor(red: r, green: g, blue: b, alpha: a)
}
}
Usage : -
let color = yourImageView.image!.getPixelColor(atLocation: location, withFrameSize: yourImageView.frame.size)
location is a CGPoint
and size is size of your imageView
The following section is taken from some Swift 3 code I'm using to sample pixels from an image to get the predominant hue which I use to generate a background for tableView rows. The mechanics for the hue selection process don't apply to your question, so I'm just providing the relevant fragment.
let colorSpace = CGColorSpaceCreateDeviceRGB() // UIExtendedSRGBColorSpace
let newImage = image.cgImage?.copy(colorSpace: colorSpace)
let pixelData = newImage?.dataProvider!.data
let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)
var hueFrequency = [Int: Double]()
hueFrequency[1] = 1 // Add one entry so this serves as a default if no hues from the image pass the filters
let nStart = 1
let mStart = 1
for n in nStart...Int(image.size.width / samplingFactor) {
for m in mStart...Int(image.size.height / samplingFactor) {
let pixelInfo: Int = ((Int(image.size.width) * m * Int(samplingFactor)) + n * Int(samplingFactor)) * 4 // bytesPerPixel
let b = CGFloat(data[pixelInfo]) / CGFloat(255.0) // cgImage bitmapinfo = rawValue 8194 -> BGRA ordering
let g = CGFloat(data[pixelInfo+1]) / CGFloat(255.0)
let r = CGFloat(data[pixelInfo+2]) / CGFloat(255.0)
let a = CGFloat(data[pixelInfo+3]) / CGFloat(255.0)
Also, note that I found the bitmapInfo value (image.cgImage!.bitmapInfo using my parameters) indicated a reordering of the RGBA sequence to BGRA, which I had to deal with in ordering the steps to pick out the data. If your colors are off, you may want to check this.

during Spritenode animation and movement appear red large x

Here is problem in which I add zoombie sprite to the scene every one second. When I add another sub animated zoombie to the zoombie node, sometimes it loads animated texture, and other times appear red large X.
func addMonster() {
let zoombieSprite = SKSpriteNode(color: SKColor.greenColor(), size: CGSizeMake(40, 60))
// Determine where to spawn the monster along the Y axis
let actualY = randRange(lower: zoombieSprite.size.height, upper: size.height - zoombieSprite.size.height)
// Position the monster slightly off-screen along the right edge,
// and along a random position along the Y axis as calculated above
zoombieSprite.position = CGPoint(x: size.width + zoombieSprite.size.width/2, y: actualY)
zoombieSprite.physicsBody = SKPhysicsBody(rectangleOfSize: zoombieSprite.size) // 1
zoombieSprite.physicsBody?.dynamic = true // 2
zoombieSprite.physicsBody?.categoryBitMask = PhysicsCategory.Monster // 3
zoombieSprite.physicsBody?.contactTestBitMask = PhysicsCategory.Projectile // 4
zoombieSprite.physicsBody?.collisionBitMask = PhysicsCategory.None // 5
addChild(zoombieSprite)
//zoombieSprite.addChild(createAnimatedZoombie())
let zoombieAnimation = SKAction.runBlock({
zoombieSprite.addChild(self.createAnimatedZoombie())
})
// Determine speed of the monster
let actualDuration = randRange(lower: 6.0, upper: 10.0)
//print("actualDuration = \(actualDuration)")
let actionMove = SKAction.moveTo(CGPoint(x: -zoombieSprite.size.width/2, y: actualY), duration: NSTimeInterval(actualDuration))
// Create the actions
let actionMoveDone = SKAction.removeFromParent()
zoombieSprite.runAction(SKAction.sequence([zoombieAnimation ,actionMove,actionMoveDone]))
}
//MARK: - ANIMATE FRAME AND MOVE ZOOMBIE
func createAnimatedZoombie () -> SKSpriteNode {
let animatedZoobieNode = SKSpriteNode(texture: spriteArray[0])
let animationFrameAction = SKAction.animateWithTextures(spriteArray, timePerFrame: 0.2)
let durationTime = SKAction.waitForDuration(0.1)
let repeatAction = SKAction.repeatActionForever(animationFrameAction)
let quenceAction = SKAction.sequence([durationTime, repeatAction])
animatedZoobieNode.runAction(quenceAction)
return animatedZoobieNode
}
Thanks very much my respectable brother Joseph Lord and Thank God i solved my problem by just dividing sprite kit atlas array count property by 2 because in this folder i had put both #2x and #3x images so when i used to get number of images from this atlas folder it used to return the number which was addition of #2x and #3x images.

Creating a Random Position for a Sprite in Swift

I have a circle sprite that I would like to move to a random position within the confines of the iOS device's screen. I am trying to do this in Swift, but I am still I beginner and I don't even know where to start. Does anyone know what to do to create a random position for the sprite? Thank you in advance!
-Vinny
Swift 3:
func spawnRandomPosition() {
let height = self.view!.frame.height
let width = self.view!.frame.width
let randomPosition = CGPoint(x:CGFloat(arc4random()).truncatingRemainder(dividingBy: height),
y: CGFloat(arc4random()).truncatingRemainder(dividingBy: width))
let sprite = SKSpriteNode()
sprite.position = randomPosition
}
Let's assume you are calling your code from the scene class:
func spawnAtRandomPosition() {
let height = self.view!.frame.height
let width = self.view!.frame.width
let randomPosition = CGPointMake(CGFloat(arc4random()) % height, CGFloat(arc4random()) % width)
let sprite = SKSpriteNode()
sprite.position = randomPosition
}
Swift 3:
let randomPosition = CGPoint( x:CGFloat( arc4random_uniform( UInt32( floor( width ) ) ) ),
y:CGFloat( arc4random_uniform( UInt32( floor( height ) ) ) )
)

Resources