How to prevent crashing when tapping off a node - swift

The code that I am writing has a problem where whenever I tap somewhere other than a node (ex. background) the app ends up crashing.
I've tried making an if let statement but it says I can't downcast a SKnode to a more optional type SKSpriteNode.
I've also tried if node.contains(position of touch).
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first
if let touchLocation = touch?.location(in: self) {
let selectedNode = nodes(at: touchLocation)[0] as! SKSpriteNode
activeObject = selectedNode
storedData = Array(activeObject.name!)
let platformStoredInt = storedData[2]
storedPlatform = Int(platformStoredInt.unicodeScalars.first!.value - Unicode.Scalar("0")!.value)
}
}
Tapping on anything other than the SKSpriteNodes that are considered objects results in a SIGABRT.

The app crashes because you are force unwrapping a value in this line:
let selectedNode = nodes(at: touchLocation)[0] as! SKSpriteNode
So instead, use:
if let selectedNode = nodes(at: touchLocation)[0] as? SKSpriteNode {
activeObject = selectedNode
storedData = Array(activeObject.name!)
let platformStoredInt = storedData[2]
storedPlatform = Int(platformStoredInt.unicodeScalars.first!.value - Unicode.Scalar("0")!.value)
}
Always try to avoid the force unwrapping (as!). Use Optional Chaining instead.
Optional chaining is a process for querying and calling properties, methods, and subscripts on an optional that might currently be nil.

Related

Is it possible to get multiple SKNodes with UITapGestureRecognizer?

I currently have multiple balls all on the same SKScene. I handle all touches and gestures within GameScene. Below is the code I use to detect which node was touched, which works.
What I am unsure of, since there are always some touchesMoved when using this on a real device, is there anyway possible for more than one node to receive a tap at the same time? If so I obviously would need to write my code differently.
#objc func tappedView(_ sender:UITapGestureRecognizer) {
if sender.state == .ended{
let point : CGPoint = sender.location(in: self.view)
var post = sender.location(in: sender.view)
post = self.convertPoint(fromView: post)
if let touchNode = self.atPoint(post) as? MyBall{
//the declaration below is just so I have somewhere to stop in the debugger
var x = 1
}
}
}
Use nodes(at:) to get multiple nodes at a point.
#objc func tappedView(_ sender:UITapGestureRecognizer) {
if sender.state == .ended{
let point : CGPoint = sender.location(in: self.view)
var post = sender.location(in: sender.view)
post = self.convertPoint(fromView: post)
for touchNode in self.nodes(at:post){
//the declaration below is just so I have somewhere to stop in the debugger
var x = 1
}
}
}
https://developer.apple.com/documentation/spritekit/sknode/1483072-nodes

Reality Composer - ar hittest not working?

Alright, Im weeding thru the provided RealityComposer game at https://developer.apple.com/videos/play/wwdc2019/609/ and am trying to figure out how to have an entity move where the user taps.
I can reference my objects in my .rc scene like this:
struct ARViewContainer: UIViewRepresentable {
let arView = ARView(frame: .zero)
func makeUIView(context: Context) -> ARView {
// arView = ARView(frame: .zero)
// Load the "Box" scene from the "Experience" Reality File
let boxAnchor = try! Experience.loadBox()
//*Notifications
setupNotifications(anchor: boxAnchor)
//*Access vars
if boxAnchor.box1 != nil {
//print(box1.position.x)
/// Set local position
boxAnchor.box1!.position = [1.0, 0.0, 0.5]
/// Set world position
//boxAnchor.box1.setPosition([0.5, 0.2, 1.5], relativeTo: nil)
}
I know this involves some form arhitest, however with the following I get the error:
UIView has no member last?
func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
//1. Get The Current Touch Location
guard let currentTouchLocation = touches.first?.location(in: self.arView),
//2. Get The Tapped Node From An SCNHitTest
let hitTestResultNode = self.arView.hitTest(currentTouchLocation, with: nil).last?.node else { return } //error here
//3. Loop Through The ChildNodes
for node in hitTestResultNode.childNodes{
//4. If The Node Has A Name Then Print It Out
if let validName = node.name{
print("Node\(validName) Is A Child Node Of \(hitTestResultNode)")
}
}
}
Im pretty lost as to whether Im going about this at all correctly. Im referencing Detect touch on SCNNode in ARKit but this does not deal with RealityComposer.
How can I do this?
The simplest way to get an Entity to move via touch is to use the built in gestures provides by Apple; which you can read more about here: Apple Documentation
To enable your gesture of choice (in this case translation), first ensure that in RealityComposer that you set the partcipates value to true on every Entity you wish to interact with.
This then adds a Has Collision component to the Entitywhich is simply:
A component that gives an entity the ability to collide with other entities that also have collision components.
Using this you can install built in gestures to do the heavy lifting for you.
Assuming we have the default RealityKit example setup in Xcode, and we have selected participates for the box, its a simple as this to enable the user to pan it using the touch location:
class ViewController: UIViewController {
#IBOutlet var arView: ARView!
override func viewDidLoad() {
super.viewDidLoad()
//1. Load The Box Anchor
let boxAnchor = try! Experience.loadBox()
//2. Check The SteelBox Has A Collision Component & Add The Desired Gesture
if let hasCollision = boxAnchor.steelBox as? HasCollision {
arView.installGestures(.translation, for: hasCollision)
}
//Add The Box To The Scene Hierachy
arView.scene.anchors.append(boxAnchor)
}
}
Alternatively if you wanted to do some heavy lifting (who doesn't!) then you could do something like this by creating a global variable which will reference the Entity that you have selected (which in this case is called Steel Box):
//Variable To Store Our Currently Selected Entity
var currentEntity: Entity?
Then using touchesBegan and touchesMoved you can something like this:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
/* Get The Current Touch Location In The ARView
Perform A HitTest For The Nearest Entity
Checks That The Tapped Entity Is The Steel Box
Set It As The Current Entity
*/
guard let touchLocation = touches.first?.location(in: arView),
let tappedEntity = arView.hitTest(touchLocation, query: .nearest, mask: .default).first?.entity,
tappedEntity.name == "Steel Box" else {
return
}
currentEntity = tappedEntity
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
/* Get The Current Touch Location In The ARView
Perform A HitTest For An Existing Plane
Move The Current Entity To The New Transfortm
Set It As The Current Entity
*/
guard let touchLocation = touches.first?.location(in: arView),
let currentEntity = currentEntity else {
return
}
if let transform = arView.hitTest(touchLocation, types: .existingPlaneUsingExtent).first?.worldTransform {
currentEntity.move(to: transform, relativeTo: nil, duration: 0.1)
}
}
Hope it helps point the in the right direction.

SCNParticleSystem not adding to SCNNode on touchesbegan

I am placing multiple SCNNodes in my view on load of my application.
On touchesbegan I am removing whatever node is tapped on.
All of this works so far so I know my code is working however just adding a SCNParticleSystem is giving me issues.
I have put two stars (**) by the lines that are not working
// On tap
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
// Register tap
let touch = touches.first!
// Get location
let location = touch.location(in: sceneView)
// Create a hit
let hitList = sceneView.hitTest(location, options: nil)
if let hitObject = hitList.first {
// Get node from hit
let node = hitObject.node
if node.name == target {
score += 3
playAudio(fileName: "two")
**let explosion = SCNParticleSystem(named: "stars.scnp", inDirectory: nil)
**node.addParticleSystem(explosion!)
node.removeFromParentNode()
// Async call
DispatchQueue.main.async {
node.removeFromParentNode()
self.scoreLabel.text = String(self.score)
}
}
}
}
How do I attach the particle to the node?
If you want to see the explosion and remove the node, just set a wait timer, for example:
let explosion = SCNParticleSystem(named: "stars.scnp", inDirectory: nil)
node.addParticleSystem(explosion!)
let waitAction = SCNAction.wait(duration: 3)
node.runAction(waitAction, completionHandler: {
self.node.removeFromParentNode()
self.scoreLabel.text = String(self.score)
})
You can post the wait action on any node, so if you have a central node in the scene, it will work with that as well

Cant drag ARKit SCNNode?

Ok, like everyone else I am having trouble dragging/translating an SCNNode in ARKit/world space. Ive looked at Dragging SCNNode in ARKit Using SceneKit and all the popular questions, as well as the code from Apple https://github.com/gao0122/ARKit-Example-by-Apple/blob/master/ARKitExample/VirtualObject.swift
Ive tried to simplify as much as possible and just did what I would in a normal scene kit game - http://dayoftheindie.com/tutorials/3d-games-graphics/t-scenekit-3d-picking-dragging/
I can get the tapped object and store the current finger pos no problem with:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
let results = gameView.hitTest(touch.location(in: gameView), types: [ARHitTestResult.ResultType.featurePoint])
//TAP Test
let hits = gameView.hitTest(touch.location(in: gameView), options: nil)
currentTapPos = getARPos(hitFeature: hitFeature) //TAP POSITION
if let tappedNode = hits.first?.node {
My issue is, however, doing this in update - there is no animation. The object just appears wherever I tap, and overall not working -
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
let results = gameView.hitTest(touch.location(in: gameView), types: [ARHitTestResult.ResultType.featurePoint])
guard let hitFeature = results.last else { return }
testNode.position = currentTapPos
I convert to SCNVector3 with this func:
func getARPos(hitFeature: ARHitTestResult)->SCNVector3
{
let hitTransform = SCNMatrix4.init(hitFeature.worldTransform)
let hitPosition = SCNVector3Make(hitTransform.m41,
hitTransform.m42,
hitTransform.m43)
return hitPosition
}
I have tried:
-translate by vector
-pan gesture (this screwed up other functions)
-SCNAction.moveTo
What can I do here? Whats wrong?
I agree with #Rickster that the Apple Code provides a much more robust example, however, I have this and it seems to work smoothly (much more so when you are using PlaneDetection (since feature points are much more sporadic):
I don't make use of touchesBegan but simply do the work in touchesMoved instead:
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
//1. Get The Current Touch Point
guard let currentTouchPoint = touches.first?.location(in: self.augmentedRealityView),
//2. Get The Next Feature Point Etc
let hitTest = augmentedRealityView.hitTest(currentTouchPoint, types: .existingPlane).first else { return }
//3. Convert To World Coordinates
let worldTransform = hitTest.worldTransform
//4. Set The New Position
let newPosition = SCNVector3(worldTransform.columns.3.x, worldTransform.columns.3.y, worldTransform.columns.3.z)
//5. Apply To The Node
nodeToDrag.simdPosition = float3(newPosition.x, newPosition.y, newPosition.z)
}
I might be going about this completely the wrong way (and if I am I would love to get feedback).
Anyway, I hope it might help... You can see a quick video of it in action here: Dragging SCNNode

Error when trying to remove node from parent

This code is in an if statement that checks if the user touches a correct button. If not returned true this code below will run. The problem is that when live is removed from parent the line let live = childNodeWithName("liveBall") as! SKSpriteNode returns this error:
fatal error: unexpectedly found nil while unwrapping an Optional
value.
This must be because childNodeWithName("liveBall") does no longer exist.
override func didMoveToView(view: SKView) {
let live = SKSpriteNode(texture: purpleTexture)
live.position = CGPointMake(self.frame.size.width * 0.68, self.frame.size.height * 0.93)
live4.name = "liveBall"
self.addChild(live)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
let live = childNodeWithName("liveBall") as! SKSpriteNode
if(intersectsNode(live)){
live.removeFromParent()
}
}
How can I avoid this error?
This means that there is no "liveBall" node as a child. Are you sure it is added? It seems that there is a typo (number 4) in:
live4.name = "liveBall"
You can try to add node like that:
var mySprite: SKSpriteNode = childNodeWithName("mySprite") as SKSpriteNode
To add safety to your function that calls RemoveFromParent(), simply add a new Boolean variable that changes itself to true when RemoveFromParent() is called and use a condition check to prevent it from occuring twice.