I'm making a maze game and i'm using a SKSpriteNode as the actual 2d maze.
I want to detect if the point on the SKSpriteNode a user is touching is black or white. I've made a UIImage which is the same image as the SKSpriteNode, and I'm using a method on the UIImage to get the pixel info. However, the UIImage seems offset compared to the SKSpriteNode. It's returning values as I move my finger around the screen, but it's incorrect. I'm guessing the UIImage is not the same size and position as the SKSpriteNode.
How can I fix this?
I use the following to get the 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've made my SKSpriteNode like this
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 here 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)")
}
}
Is the size of your image the same size as your SKScene
?
In touchesBegan
function, Try getting the location of your touch inside bgImage
instead of the SKScene
.
theColor = (mazeMap.getPixelColor(touch.locationInNode(bgImage)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With