How encode GKComponentSystem<GKComponent> object - swift

I'm stuck trying to encode an array.
I have a class as following:
class EnemyMoveComponentSystem: GKComponentSystem<GKComponent> {
func updateWithDeltaTime(seconds: TimeInterval, gameScene: GameScene) {
for component in components {
if let enemyMoveComponent = component as? EnemyMoveComponent {
enemyMoveComponent.update(deltaTime: seconds, gameScene: gameScene)
}
}
}
}
Then I declared an array as following:
var enemyMoveComponentSystems: [EnemyMoveComponentSystem] = []
However, when i tried to encode the array as below I get error:
override func encode(with aCoder: NSCoder) {
aCoder.encode(enemyMoveComponentSystems, forKey: "Scene.enemyMoveComponentSystems")
}
Any help is appreciated.

Related

How do you access SKNode subclass methods from SKNode.children array?

I have a scene with a number of children which are sub-classed SKNodes. I am trying to access a method for each of the child nodes, but am getting the error "Value of type 'SKNode' has no member '[member name]".
All on Swift 5 on Xcode 10.2 (if that's relevant?).
import SpriteKit
class GameScene: SKScene {
override func didMove(to view: SKView) {
let slim = NamedNode(name: "Slim Shady")
let snoop = NamedNode(name: "Snoop Dog")
let shaggy = NamedNode(name: "Shaggy")
self.addChild(slim)
self.addChild(snoop)
self.addChild(shaggy)
for child in self.children {
child.whatsMyName()
// ERROR: Value of type 'SKNode' has no member 'whatsMyName'
}
}
}
class NamedNode: SKNode {
var standup = false
init(name: String) {
super.init()
self.name = name
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func whatsMyName() {
print("My name is ", name as Any)
if self.name == "Slim Shady" {
standup = true
}
}
}
How can I access these methods from the Scene.children array? Is it possible or should I change tact?
Thanks!
It is said here that
The children of an SKScene are of SKNode type. You want to access a property of an SKNode subclass. At compile time, the children are seen as SKNodes.
You should try casting your child, something like
for child in self.children {
(child as? NamedNode).whatsMyName()
}
Have in mind that downcasting is usually a code smell.

How to detect SCNPhysics Intersection between two GKEntities(SCNNodes) in a GKComponent for in SceneKit

I am attempting to detect the intersection of two scnnodes in SceneKit. They are registered as GKEntities. I want to associate a component to both entities that will detect the intersection of their physics bodies using SCNPhysicsContactDelegate, but I don't want to do this in the view controller as I know it is not best practice and it would make it difficult to register that as a component. Any help would be appreciated.
Thanks for the assistance,
Montreaux
import Foundation
import SpriteKit
import GameplayKit
import SceneKit
class MeleeComponent: GKComponent, SCNPhysicsContactDelegate {
let damage: CGFloat
let destroySelf: Bool
let damageRate: CGFloat
var lastDamageTime: TimeInterval
let aoe: Bool
// let sound: SKAction
let entityManager: EntityManager
init(damage: CGFloat, destroySelf: Bool, damageRate: CGFloat, aoe: Bool, entityManager: EntityManager) {
self.damage = damage
self.destroySelf = destroySelf
self.damageRate = damageRate
self.aoe = aoe
// self.sound = sound
self.lastDamageTime = 0
self.entityManager = entityManager
super.init()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func update(deltaTime seconds: TimeInterval) {
super.update(deltaTime: seconds)
// Get required components
guard let teamComponent = entity?.component(ofType: TeamComponent.self),
let spriteComponent = entity?.component(ofType: SpriteComponent.self) else {
return
}
// Loop through enemy entities
var aoeDamageCaused = false
let enemyEntities = entityManager.entitiesForTeam(teamComponent.team.oppositeTeam())
for enemyEntity in enemyEntities {
// Get required components
guard let enemySpriteComponent = enemyEntity.component(ofType: SpriteComponent.self),
let enemyHealthComponent = enemyEntity.component(ofType: HealthComponent.self) else {
continue
}
// Check for intersection
if (spriteComponent.node.frame.intersects(enemySpriteComponent.node.frame)) {
// Check damage rate
if (CGFloat(CACurrentMediaTime() - lastDamageTime) > damageRate) {
// Cause damage
// spriteComponent.node.parent?.run(sound)
if (aoe) {
aoeDamageCaused = true
} else {
lastDamageTime = CACurrentMediaTime()
}
// Subtract health
enemyHealthComponent.takeDamage(damage)
// Destroy self
if destroySelf {
entityManager.remove(entity!)
}
}
}
}
if (aoeDamageCaused) {
lastDamageTime = CACurrentMediaTime()
}
}
}
In SCNPhysicsWorld, There are a few APIs can help you.
such as
func contactTestBetween(_ bodyA: SCNPhysicsBody, _ bodyB: SCNPhysicsBody, options: [SCNPhysicsWorld.TestOption : Any]? = nil) -> [SCNPhysicsContact]
It's similar to the code in your example:
if (spriteComponent.node.frame.intersects(enemySpriteComponent.node.frame))
But it's in SceneKit and will give you more information about the contact.

How to make singleton class from class, which inherits from nsobject and nscoding?

I am trying to make the game settings which loads, saves itself, and makes it singleton class. All my efforts lead to failure, XCode asks me "Cannot invoke initializer for type "Settings" with no arguments". How can I fix this?
This is the code:
class Settings: NSObject, NSCoding {
static let sharedInstance = Settings()
var currentLevel: Int
var positionOfPlayer: [Int]?
var sounds: Bool
var shape: String
var completedLevels: [Int: Bool]
init?(currentLevel: Int, positionOfPlayer: [Int]?, sounds: Bool, shape: String, completedLevels: [Int: Bool]) {
self.currentLevel = currentLevel
self.sounds = sounds
self.shape = shape
self.completedLevels = completedLevels
if let position = positionOfPlayer as [Int]? {
self.positionOfPlayer = position
}
super.init()
}
required convenience init?(coder aDecoder: NSCoder) {
let currentLevel = aDecoder.decodeObjectForKey(SettingNames.nameOfCurrentLevel) as? Int
let completedLevels = aDecoder.decodeObjectForKey(SettingNames.nameOfCompletedLevels) as? [Int: Bool]
let positionOfPlayer = aDecoder.decodeObjectForKey(SettingNames.positionOfPlayerOnCurrentLevel) as? [Int]
let sounds = aDecoder.decodeObjectForKey(SettingNames.nameOfSounds) as? Bool
let shape = aDecoder.decodeObjectForKey(SettingNames.nameOfShapes) as? String
self.init(currentLevel: currentLevel!, positionOfPlayer: positionOfPlayer, sounds: sounds!, shape: shape!, completedLevels: completedLevels!)
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(currentLevel, forKey: SettingNames.nameOfCurrentLevel)
aCoder.encodeObject(completedLevels, forKey: SettingNames.nameOfCompletedLevels)
if let position = positionOfPlayer as [Int]? {
// If game canceled or ended during playing, it saves the current player position.
// Next time, when player open the game, it will continue
aCoder.encodeObject(position, forKey: SettingNames.positionOfPlayerOnCurrentLevel)
}
aCoder.encodeBool(sounds, forKey: SettingNames.nameOfSounds)
aCoder.encodeObject(shape, forKey: SettingNames.nameOfShapes)
}
}
You're trying to access a constructor which accepts no parameters which was not implemented for the current class. Try overriding the init method, that should remove the error.
override init(){
// some code
}
Here's a full example I've tried:
import Foundation
class Settings : NSObject, NSCoding {
static let sharedInstance = Settings()
var a: String?
var b: String?
convenience init(a: String, b: String){
self.init()
self.a = a
self.b = b
}
override init(){
}
required init?(coder aDecoder: NSCoder) {
}
func encodeWithCoder(aCoder: NSCoder) {
}
}
Just a point of view: a Singleton that requires you to pass parameters in order to configure it does no longer behave like a singleton.

Encoding/Decoding an array of objects which implements a protocol in Swift 2

I have got a class that inherits from NSObject and I want it to be NSCoding compliant. But I ran into trouble while encoding an array of objects which should implement a protocol.
protocol MyProtocol {
var myDescription: String { get }
}
class DummyClass: NSObject, NSCopying, MyProtocol {
var myDescription: String {
return "Some description"
}
func encodeWithCoder(aCoder: NSCoder) {
// does not need to do anything since myDescription is a computed property
}
override init() { super.init() }
required init?(coder aDecoder: NSCoder) { super.init() }
}
class MyClass: NSObject, NSCoding {
let myCollection: [MyProtocol]
init(myCollection: [MyProtocol]) {
self.myCollection = myCollection
super.init()
}
required convenience init?(coder aDecoder: NSCoder) {
let collection = aDecoder.decodeObjectForKey("collection") as! [MyProtocol]
self.init(myCollection: collection)
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(myCollection, forKey: "collection")
}
}
For aCoder.encodeObject(myCollection, forKey: "collection") I get the error:
Cannot convert value of type '[MyProtocol]' to expected argument type 'AnyObject?'
OK, a protocol obviously is not an instance of a class and so it isn't AnyObject? but I've no idea how to fix that. Probably there is a trick that I'm not aware? Or do you do archiving/serialization differently in Swift as in Objective-C?
There's probably a problem with let collection = aDecoder.decodeObjectForKey("collection") as! [MyProtocol], too but the compiler doesn't complain yet…
I've just found the solution myself: The key is to map myCollection into [AnyObject] and vice-versa, like so:
class MyClass: NSObject, NSCoding {
let myCollection: [MyProtocol]
init(myCollection: [MyProtocol]) {
self.myCollection = myCollection
super.init()
}
required convenience init?(coder aDecoder: NSCoder) {
let collection1 = aDecoder.decodeObjectForKey("collection") as! [AnyObject]
let collection2: [MyProtocol] = collection1.map { $0 as! MyProtocol }
self.init(myCollection: collection2)
}
func encodeWithCoder(aCoder: NSCoder) {
let aCollection: [AnyObject] = myCollection.map { $0 as! AnyObject }
aCoder.encodeObject(aCollection, forKey: "collection")
}
}
I know your title specifies Swift 2, but just for reference, for a similar problem I was working on, I found that in Swift 3, you don't need to convert anymore to AnyObject.
The following works for me in Swift 3 (using your example):
class MyClass: NSObject, NSCoding {
let myCollection: [MyProtocol]
init(myCollection: [MyProtocol]) {
self.myCollection = myCollection
super.init()
}
required convenience init?(coder aDecoder: NSCoder) {
let collection = aDecoder.decodeObject(forKey: "collection") as! [MyProtocol]
self.init(myCollection: collection)
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encode(aCollection, forKey: "collection")
}
}

How do edit a sprite based on its name?

So in my game i have a function that spawns coins,they are given the name "coin", Now I have no way to reference the coins,example to kill them or move them.So what I'm trying to do is make a reference to be able to use in my code to just change its zPosition.
Everytime I run my app and have a function run that uses the coinRef [ex. to change the zPosition], the app crashes with the error:
'Thread 1 EXC_BAD_INSTRUCTION (code=EXC_1386_INVOP, subcode=0x0)'
Heres my code:
let coinRef: SKSpriteNode = self.childNodeWithName("coin")! as! SKSpriteNode
func hideCoins() {
coinRef.zPosition = -1
}
func showCoins() {
coinRef.zPosition = 101
}
func killCoins() {
coinRef.removeFromParent()
}
Looking at what you write
So in my game i have a function that spawns coins,they are given the name "coin"
it looks like there are multiple coins in your scene. As you can imagine a single name coin is not enough to univocally identify more then 1 coin :)
We'll need a way do identity multiple coins.
1. The Coin class
class Coin: SKSpriteNode {
private static var lastID: UInt = 0
let id:UInt
init() {
self.id = Coin.lastID++
let texture = SKTexture(imageNamed: "coin")
super.init(texture: texture, color: UIColor.clearColor(), size: texture.size())
self.name = "coin"
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
As you can see Coin has an internal mechanism to assign a new id to each new instance. You can use this id to reference the coins in your scene.
let coin0 = Coin()
coin0.id // 0
let coin1 = Coin()
coin1.id // 1
let coin2 = Coin()
coin2.id // 2
2. Managing your coins
class GameScene: SKScene {
func retrieveCoin(id:UInt) -> Coin? {
return children.filter { ($0 as? Coin)?.id == id }.first as? Coin
}
func hideCoin(id:UInt) {
retrieveCoin(id)?.hidden = true
}
func showCoin(id:UInt) {
retrieveCoin(id)?.hidden = true
}
func deleteCoin(id:UInt) {
retrieveCoin(id)?.removeFromParent()
}
}
The retrieveCoin method returns (if does exist) a coin with the specified id. Otherwise nil is returned.
The hideCoin and showCoin do change the hidden property to change its visibility.
Finally deleteCoin remove from the scene the Coin with the specified id.
Try this. Initialise coinRef before the didMoveToView function, and then give coinRef its value in the didMoveToView function.
class scene : SKScene {
let coinRef: SKSpriteNode = SKSpriteNode()
override func didMoveToView(view: SKView) {
coinRef: SKSpriteNode = self.childNodeWithName("coin")! as! SKSpriteNode
}
func hideCoins() {
coinRef.zPosition = -1
}
func showCoins() {
coinRef.zPosition = 101
}
func killCoins() {
coinRef.removeFromParent()
}
}