I have a scene with multiple nodes. I want to select a node by tapping it (if I tap nothing I want nothing to happen) and make him follow my finger only on XY axis (I know position on Z axis). Is there any method that converts location in view to SceneKit coords?
After few researches I found this and it's exactly what I want, but I don't get the code. Can somebody explain me or help me figure how can I solve my problem?
https://www.youtube.com/watch?v=xn9Bt2PFp0g
func CGPointToSCNVector3(view: SCNView, depth: Float, point: CGPoint) -> SCNVector3 {
let projectedOrigin = view.projectPoint(SCNVector3Make(0, 0, depth))
let locationWithz = SCNVector3Make(Float(point.x), Float(point.y), projectedOrigin.z)
return view.unprojectPoint(locationWithz)
}
Looks like was pretty simple, I've made a function that gets 3 parameters. View is the SCNView where scene is attached to, depth is the z value of node, and point is a CGPoint that represents projection of 3D scene on screen.
This is Alec Firtulescu's answer as an extension for watchOS (convert it to iOS by changing WKInterfaceSCNScene to SCNView):
extension CGPoint {
func scnVector3Value(view: WKInterfaceSCNScene, depth: Float) -> SCNVector3 {
let projectedOrigin = view.projectPoint(SCNVector3(0, 0, depth))
return view.unprojectPoint(SCNVector3(Float(x), Float(y), projectedOrigin.z))
}
}
Related
I'm currently working on a game in scenekit with swift, and i've got a spaceship flying around. I'm using the following code to make the camera follow the spaceship:
func renderer(_ renderer: SCNSceneRenderer, updateAtTime time: TimeInterval) {
updateCameraPosition()
}
func updateCameraPosition () {
let currentPosition = player.node.presentation.position
let x: Float = lerp(a: Float(prevCameraPosition.x), b: currentPosition.x, t: 0.03)
let z: Float = lerp(a: Float(prevCameraPosition.z), b: currentPosition.z, t: 0.03) + (cameraZoom/2)
let vector = SCNVector3(x: x, y: cameraZoom, z: z)
cameraNode.runAction(SCNAction.move(to: vector, duration: 0.2))
prevCameraPosition = currentPosition
}
func lerp (a: Float, b: Float, t: Float) -> Float {
return (1 - t) * a + t * b;
}
in addition to just following the ship, it add's some nice offset motion when you change directions for a nice fluid camera.
The problem i'm facing is the ship glitches back and forth a good portion of the time, it always moves in the correct directions, but it almost looks like the ship position is getting reset back a few frames. You can see this in action with this video.
Without the camera follow code, the ship moves much smoother, as you can see in this video
Can anybody see anything wrong with my code that is maybe inefficient? Maybe there is a more optimized way to do this? Any tips/resources/advice is greatly appriciated!
You need to stop the previous SCNAction before applying new SCNAction.
To add an action with a key you use the
cameraNode.runAction(SCNAction, forKey: String)
method.
Now you can remove a specific action by that key
cameraNode.removeAction(forKey: String)
I have an issue with ARkit, I use ARWorldTrackingConfiguration and when I have a SCNNode one meter away from me, when I use Iphone X and move to the SCNNode, the Z position of my camera SCNNode updates and I know that I am closer to the node, but with other Iphones (Iphone 8) I don't get an update to Z position.
Also with GPS even with kCLLocationAccuracyBestForNavigation I don't have accuracy.
How can I know that I am closer to the SCNNode?? Thank you
implementing ARSCNViewDelegate in your ViewController, it will be called the renderer:updateAtTime callback once per frame.
Inside this function you can get the position of your camera relative to the real world calling sceneView.session.currentFrame.camera.transform which is a simd_float4x4. You can access the current position of your camera with transform.columns.3 and peeking the x,y,z field from it. With these coordinates you can calculate the distance, such the Euclidean distance with these functions
func distanceTravelled(xDist:Float, yDist:Float, zDist:Float) -> Float{
return sqrt((xDist*xDist)+(yDist*yDist)+(zDist*zDist))
}
func distanceTravelled(between v1:SCNVector3,and v2:SCNVector3) -> Float{
let xDist = v1.x - v2.x
let yDist = v1.y - v2.y
let zDist = v1.z - v2.z
return distanceTravelled(xDist: xDist, yDist: yDist, zDist: zDist)
}
Remember to convert the coordinates of the nodes to worldCoordinates -> node.worldPosition with node an instance of SCNNode
As always I need your help. I need to draw a straight line from a start value (declared as SCNVector3) and connected to the position in the real world till the end point.
Can someone explain to me with some lines of code how can I do it?
Thank you!
You'll need to implement:
touchesBegan, touchesMoved, touchesEnded, touchesCancelled
for your camera view controller.
In touchesBegan you will need to make hitTest for current ARFrame in the UITouch location. Then you'll have your startPosition and your lastTouch, which is your start UITouch.
Then you will need to add timer with 0.016_667 interval (60Hz) which will update your last touch position with hitTest when you camera moves. Same you'll do in touchesMoved function. And in touchesMoved you'll also update your lastTouch. So at this point you'll have your startPosition and currentPosition, which is SCNVector3. And you can just redraw SCNCylinder (with 0.001m radius for example) for those positions if you need straight line.
At last step in touchesEnded you'll fix your line, or if touchesCancelled you will remove it and clear lastTouch.
UPD
If you need 2D line on the screen, then you'll need to use projectPoint for your ARSceneView.
3D line drawing
For drawing 3D line you could SCNGeometry use extension:
extension SCNGeometry {
class func line(from vector1: SCNVector3, to vector2: SCNVector3) -> SCNGeometry {
let indices: [Int32] = [0, 1]
let source = SCNGeometrySource(vertices: [vector1, vector2])
let element = SCNGeometryElement(indices: indices, primitiveType: .line)
return SCNGeometry(sources: [source], elements: [element])
}
}
Using:
let line = SCNGeometry.line(from: startPosition, to: endPosition)
let lineNode = SCNNode(geometry: line)
lineNode.position = SCNVector3Zero
sceneView.scene.rootNode.addChildNode(lineNode)
I have the position and orientation of my camera, the CGPoint touch location on the screen, I need the line (preferably vector) in the direction that I touched on the screen in my 3d SCNNode environment, how can I get this?
A code snippet would be very helpful.
You can use the SCNSceneRenderer.unprojectPoint(_:) method for this.
This method, which is implemented by SCNView, takes the coordinates of your point as a SCNVector3. Set the first two elements in the coordinate space of your view. Apple describes the use of the third element:
The z-coordinate of the point parameter describes the depth at which to unproject the point relative to the near and far clipping planes of the renderer’s viewing frustum (defined by its
pointOfView
node). Unprojecting a point whose z-coordinate is 0.0 returns a point on the near clipping plane; unprojecting a point whose z-coordinate is 1.0 returns a point on the far clipping plane.
You are not looking for the location of these points, but for the line that connects them. Just subtract both to get the line.
func getDirection(for point: CGPoint, in view: SCNView) -> SCNVector3 {
let farPoint = view.unprojectPoint(SCNVector3Make(point.x, point.y, 1))
let nearPoint = view.unprojectPoint(SCNVector3Make(point.x, point.y, 0))
return SCNVector3Make(farPoint.x - nearPoint.x, farPoint.y - nearPoint.y, farPoint.z - nearPoint.z)
}
I have 2 SKSpriteNode:
a simple square (A)
the same square with a rotation (-45°) (B)
I need to check, at any time, if the center of another SKSpriteNode (a ball) is inside one of these squares.
The ball and the squares have the same parent (the main scene).
override func update(_ currentTime: TimeInterval) {
let spriteArray = self.nodes(at: ball.position)
let arr = spriteArray.filter {$0.name == "square"}
for square in arr {
print(square.letter)
if(square.contains(self.puck.position)) {
print("INSIDE")
}
}
}
With the simple square (A), my code works correctly. The data are right. I know, at any time, if the CGPoint center is inside or outside the square.
But with the square with the rotation (B), the data aren't as desired. The CGPoint is detected inside as soon as it's in the square which the diamond-shape is contained.
The SKSpriteNode squares are created via the level editor.
How can I do to have the correct result for the diamond-shape?
EDIT 1
Using
view.showsPhysics = true
I can see the bounds of all the SKSpriteNode with physicsBody. The bounds of my diamond-square is the diamond-square and not the grey square area.
square.frame.size -> return the grey area
square.size -> return the diamond-square
In the Apple documentation, func nodes(at p: CGPoint) -> [SKNode], the method is about node and not frame, so why it doesn't work?
There are many ways to do it, usually I like to work with paths so , if you have a perfect diamond as you describe I would like to offer a different way from the comments, you could create a path that match perfectly to your diamond with UIBezierPath because it have the method containsPoint:
let f = square.frame
var diamondPath = UIBezierPath.init()
diamondPath.moveToPoint(CGPointMake(f.size.width-f.origin.x,f.origin.y))
diamondPath.addLineToPoint(CGPointMake(f.origin.x,f.size.height-f.origin.y))
diamondPath.addLineToPoint(CGPointMake(f.size.width-f.origin.x,f.size.height))
diamondPath.addLineToPoint(CGPointMake(f.size.width,f.size.height-f.origin.y))
diamondPath.closePath()
if diamondPath.containsPoint(<#T##point: CGPoint##CGPoint#>) {
// point is inside diamond
}