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
Related
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
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.
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.
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
I have a game that has 3 SKSpriteNodes that the user can move around using the touchesBegan and touchesMoved. However, when the users moves nodeA and passes another node called nodeB, nodeB follows nodeA and so on.
I created an array of SKSpriteNodes and used a for-loop to make life easier.
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let nodes = [nodeA, nodeB, nodeC]
for touch in touches {
let location = touch.location(in: self)
for node in nodes {
if node!.contains(location) {
node!.position = location
}
}
}
}
Everything is working except when nodeA is moving and cross paths with nodeB, nodeB follows nodeA.
How can I make it so that when the user is moving nodeA and nodeA passes through nodeB that nodeB would not follow nodeA.
Instead of doing slow searches, have a special node variable for your touched node
class GameScene
{
var touchedNodeHolder : SKNode?
override func touchesBegan(.....)
{
for touch in touches {
guard touchNodeHandler != nil else {return} //let's not allow other touches to interfere
let pointOfTouch = touch.location(in: self)
touchedNodeHolder = nodeAtPoint(pointOfTouch)
}
}
override func touchesMoved(.....)
{
for touch in touches {
let pointOfTouch = touch.location(in: self)
touchedNodeHolder?.position = pointOfTouch
}
}
override func touchesEnded(.....)
{
for touch in touches {
touchedNodeHolder = nil
}
}
}
After some experimenting, I found a way to go about this problem.
Instead of selecting the node by the position of the touch, I found that selecting the node by its name property did the trick.
The code shown is implemented inside the touchesMoved and touchesBegan methods
//name of the nodes
let nodeNames = ["playO", "playOO", "playOOO", "playX", "playXX", "playXXX"]
//the actual nodes
let player = [playerO, playerOO, playerOOO, playerX, playerXX, playerXXX]
for touch in touches {
let pointOfTouch = touch.location(in: self)
let tappedNode = atPoint(pointOfTouch)
let nameOfTappedNode = tappedNode.name
for i in 0..<nodeNames.count {
if nameOfTappedNode == nodeNames[i] {
z += 1
player[i]!.zPosition = CGFloat(z)
print(player[i]!.zPosition)
player[i]!.position = pointOfTouch
}
}
}