SpriteKit: How can I get the pixel color from a point in SKSpriteNode?

I make a game in a maze, and I use SKSpriteNode as a real 2d maze.

I want to determine if a point on SKSpriteNode is a user tangent black or white. I created UIImage, which is the same image as SKSpriteNode, and I use the UIImage method to get pixel information. However, UIImage seems biased compared to SKSpriteNode. It returns values ​​when I move my finger across the screen, but it is incorrect. I assume that UIImage is not the same size and position as SKSpriteNode.

How can i fix this?

I use the following to get pixel data

extension UIImage { func getPixelColor(pos: CGPoint) -> UIColor { let pixelData = CGDataProviderCopyData(CGImageGetDataProvider(self.CGImage)) 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]) / 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: r, green: g, blue: b, alpha: a) } 

}

I made my SKSpriteNode this way

 var theColor : UIColor = UIColor() var bgImage = SKSpriteNode(imageNamed: mazeImageName) var mazeMap : UIImage = UIImage(named: mazeImageName)! override func didMoveToView(view: SKView) { bgImage.position = CGPointMake(self.size.width/2, self.size.height/2) bgImage.size = CGSize(width: self.size.width, height: self.size.height) self.addChild(bgImage) } 

And this is where I actually get the pixel color

 override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { if let touch = touches.first { theColor = (mazeMap.getPixelColor(touch.locationInNode(self))) var red : CGFloat = CGFloat() var green : CGFloat = CGFloat() var blue : CGFloat = CGFloat() var alpha : CGFloat = CGFloat() theColor.getRed(&red, green: &green, blue: &blue, alpha: &alpha) print("Red: \(red), Green: \(green), Blue: \(blue), Alpha: \(alpha)") } } 
+6
ios swift sprite-kit
source share
1 answer

Is the size of your image the same size as your SKScene ?

In the touchesBegan function, try to get the location of your contact inside bgImage instead of SKScene .

 theColor = (mazeMap.getPixelColor(touch.locationInNode(bgImage))) 
+1
source share

All Articles