How to get a SCNNode to face the current camera position? - swift

I'm currently programming an AR-App, which starts with placing a SCNNode (table). First the app searches for a horizontal plane and whenever a surface was found, the object is shown, but not placed yet. While it is not placed, I want the object to face the camera at all times, but I'm having trouble to find the current position of the camera and also updating the object every frame.
Currently, the object is facing the world coordinates. So when I start the app and a horizontal plane was found - the object appears and faces to the starting point of the world coordinates (wherever I started the app)
Can anybody help me, how to get the vector from the camera position and make the object updates it's direction every frame?
var tableNode : SCNNode! // Node of the actual table
var trackingPosition = SCNVector3Make(0.0, 0.0, 0.0)
let trans = SCNMatrix4(hitTest.worldTransform)
self.trackingPosition = SCNVector3Make(trans.m41, trans.m42, trans.m43)
self.tableNode.position = self.trackingPosition

The functionality you are trying to implement is called billboarding. To achieve this effect you need to set the SCNLookAtConstraint using the scene's .pointOfView as the target.
you can remove
self.trackingPosition = SCNVector3Make(trans.m41, trans.m42, trans.m43)
self.tableNode.position = self.trackingPosition
and use:
// set constraint to force the node to always face camera
let constraint = SCNLookAtConstraint(target:sceneView.pointOfView)
constraint.isGimbalLockEnabled = true
self.tableNode.constraints = [constraint] // constraint can cause node appear flipped over X axis

You should implement ARSCNViewDelegate and use the renderer method renderer(_:updateAtTime:) where you every frame get the camera position from sceneView.pointOfView. This allows you to then use the SCNNode method look(at:) to transform the nodes coordinate system towards the camera.
func renderer(_ renderer: SCNSceneRenderer, updateAtTime time: TimeInterval) {
if let camera = sceneView.pointOfView {
tableNode.look(at: camera.worldPosition)
}
}

Related

Unity instantiate object at a certain direction based of a spatial anchor

Having a spatial anchor as a reference point, I wanted to create an object that does not change its location that reference to the spatial anchor.
When creating and saving the initial location of the object that will be spawned later using prefab. I make use of the difference of the x,y,z coordinate between the spatial anchor and the object and saved it in the cloud. After that, making use of the difference of the x,y,z to load the prefab back to it original position.
when creating the object based off the spatial anchor
However, upon restarting the application at a different point, the prefab will be shifted based on the start up position of the hololens. Based on what I know, the initial position of the hololens when it starts up in (0,0,0). Hence, the spatial anchor coordinate will be different and causing the prefab to be loaded at a different direction.
upon starting up the app at different location
Is there any way or solution that I can implement to make the prefab load at the same place as where it is created without it being affected by the hololens location?
If your prefab is a child of the anchor you could do something like this to save the position relative to the anchor:
var localPos = spawned.transform.localPosition;
var localRot = spawned.transform.localEulerAngles;
var localSca = spawned.transform.localScale;
var prefab = new Prefab
{
AnchorId = anchorId,
PosX = localPos.x,
PosY = localPos.y,
PosZ = localPos.z,
RotX = localRot.x,
RotY = localRot.y,
RotZ = localRot.z,
ScaX = localSca.x,
ScaY = localSca.y,
ScaZ = localSca.z
};
Save prefab to the cloud.
And then when you are starting a new session and you locate the anchor, you'd spawn the prefab as a child of the anchor and set the transform from the data you stored previously:
spawned.transform.localPosition = new Vector3(prefab.PosX, prefab.PosY, prefab.PosZ);
spawned.transform.localRotation = Quaternion.Euler(prefab.RotX, prefab.RotY, prefab.RotZ);
spawned.transform.localScale = new Vector3(prefab.ScaX, prefab.ScaY, prefab.ScaZ);

Detect other Spritenode within range of Spritenode?

I have a (moving) sprite node.
I'd like to detect other (moving) sprite nodes within a certain range of this node. Once one is detected, it should execute an action.
The playing an action part is no problem for me but I can't seem to figure out the within-range detection. Does have any ideas how to go about this?
A simple, but effective way to do this is comparing the position's in your scene's didEvaluateActions method. didEvaluateActions gets called once a frame (after actions have been evaluated but before physics simulation calculations are run). Any new actions you trigger will start evaluating on the next frame.
Since calculating the true distance requires a square root operation (this can be costly), we can write our own squaredDistance and skip that step. As long as our range/radius of detect is also squared, our comparisons will work out as expected. This example shows detect with a "true range" of 25.
// calculated the squared distance to avoid costly sqrt operation
func squaredDistance(p1: CGPoint, p2: CGPoint) -> CGFloat {
return pow(p2.x - p1.x, 2) + pow(p2.x - p1.x, 2)
}
// override the didEvaluateActions function of your scene
public override func didEvaluateActions() {
// assumes main node is called nodeToTest and
// all the nodes to check are in the array nodesToDetect
let squaredRadius: CGFloat = 25 * 25
for node in nodesToDetect {
if squareDistance(nodeToTest.position, p2: node.position) < squaredRadius {
// trigger action
}
}
}
If the action should only trigger once, you'll need to break out of the loop after the first detection and add some sort of check so it does not get triggered again on the next update without the proper cool down period. You may also need to convert the positions to the correct coordinate system.
Also, take a look at the documentation for SKScene. Depending on your setup, didEvaluateActions might not be the best choice for you. For example, if your game also relies on physics to move your nodes, it might be best to move this logic to didFinishUpdate (final callback before scene is rendered, called after all actions, physics simulations and constraints are applied for the frame).
Easiest way I can think of without killing performance is to add a child SKNode with an SKPhysicsBody for the range you want to hit, and use this new nodes contactBitMask to determine if they are in the range.
Something like this (pseudo code):
//Somewhere inside of setup of node
let node = SKNode()
node.physicsBody = SKPhysicsBody(circleOfRadius: 100)
node.categoryBitMask = DistanceCategory
node.contactBitMask = EnemyCategory
sprite.addNode(node)
//GameScene
func didBeginContact(...)
{
if body1 contactacted body2
{
do something with body1.node.parent
//we want parent because the contact is going to test the bigger node
}
}

How do run an SKAction on a group of SKSpriteNodes with the same name?

I'm making a game in Xcode 6 using spriteKit and swift. I have a plane on scene, and to make it look like its moving, I'm create clouds off the scene to the left of the screen. I then us an SKAction to move the cloud to the right side of the screen. This works great. You then click to jump off the plane, and the plane moves up off the scene. I then have it start making the clouds on the bottom of the scene, then they move up off the top of the scene, but the problem is, the already existing clouds still have to move to the right side of the screen. My question is, how do I make it so all of the existing clouds stop their action that moves them to the right, then begin to move up exactly where they are? How do I access the group of existing clouds all at the same time once they have been created? I also want the clouds to slow down after you have jumped when you tap the screen to open your parachute, but this should be able to be done by ending the SKAction that moves the clouds, then using another SKAction on them that moves them up slower, but I don't know how to access a group of SKSpriteNodes.
Here is the code that I have to make the clouds:
//This is how the cloud is first declared at the top of the .swift file
var cloud = SKSpriteNode()
//This is the function that runs every certain interval through an NSTimer
func createCloud()
{
cloud = SKSpriteNode(imageNamed: "cloud")
cloud.xScale = 1.25
cloud.yScale = cloud.xScale/2
cloud.zPosition = -1
self.addChild(cloud)
if personDidJump == false
{
let moveRight = SKAction.moveToX(CGRectGetWidth(self.frame) + CGRectGetWidth(cloud.frame), duration: cloudSpeed)
var apple = CGRectGetWidth(self.frame)
var randomNumber:CGFloat = CGFloat(arc4random_uniform(UInt32(apple)))
cloud.position = CGPointMake(-CGRectGetWidth(cloud.frame), randomNumber)
cloud.runAction(moveRight)
}
if personDidJump == true
{
let moveUp = SKAction.moveToY(CGRectGetHeight(self.frame) + CGRectGetWidth(cloud.frame), duration: cloudSpeed)
var apple = CGRectGetWidth(self.frame)
var randomNumber:CGFloat = CGFloat(arc4random_uniform(UInt32(apple)))
cloud.position = CGPointMake(randomNumber, -CGRectGetHeight(cloud.frame))
cloud.runAction(moveUp)
}
}
Also, should I be worried about deleting the clouds when they move off the scene? Or can I just leave them there because you can't see them, and from what I've seen, they don't lag you.
Any help would be greatly appreciated. Thank you.
-Callum-
Put your clouds in an array. When your player jumps (or whenever you need to move them) run through the array and run your action on each cloud.
stackoverflow.com/a/24213529/3402095
^ That is where I found my answere ^
When you make a node give it a name:
myNode.name = "A Node Name"
self.addChild(myNode)
If there are a lot of these nodes, later you can change properties or preform SKAcions on these nodes or do whatever you want to do by using enumerateChildNodesWithName:
self.enumerateChildNodesWithName("A Node Name")
{
myNode, stop in
myNode.runAction(SKAction.moveToY(CGRectGetHeight(self.Frame), duration: 1)
}
I hope this is useful to whoever may need it.

SpriteKit - How do I check if a certain set of coordinates are inside an SKShapeNode?

In my game, I'm trying to determine what points to dole out depending on where an arrow hits a target. I've got the physics and collisions worked out and I've decided to draw several nested circular SKShapeNodes to represent the different rings of the target.
I'm just having issues working out the logic involved in checking if the contact point coordinates are in one of the circle nodes...
Is it even possible?
The easiest solution specific to Sprite Kit is to use the SKPhysicsWorld method bodyAtPoint:, assuming all of the SKShapeNode also have an appropriate SKPhysicsBody.
For example:
SKPhysicsBody* body = [self.scene.physicsWorld bodyAtPoint:CGPointMake(100, 200)];
if (body != nil)
{
// your cat content here ...
}
If there could be overlapping bodies at the same point you can enumerate them with enumerateBodiesAtPoint:usingBlock:
You can also compare the SKShapeNode's path with your CGPoint.
SKShapeNode node; // let there be your node
CGPoint point; // let there be your point
if (CGPathContainsPoint(node.path, NULL, point, NO)) {
// yepp, that point is inside of that shape
}

In Away3d particles system, adding a particleFollowNode to the particleAnimationSet make BillboardNode did not work

I've made a snow effect with particles system in away3d, but when I added a particleFollowNode to the ParticleAnimationSet,then the billboardNode did not work. Anybody knows how to fix this bug? Thanks for your help.
ActionScript:
//setup the particle animation set
_particleAnimationSet = new ParticleAnimationSet(true, true);
_particleAnimationSet.addAnimation(new ParticleVelocityNode(ParticlePropertiesMode.LOCAL_STATIC));
_particleAnimationSet.addAnimation(new ParticlePositionNode(ParticlePropertiesMode.LOCAL_STATIC));
particleFollowNode=new ParticleFollowNode(true,true);
//add particleFollowNode for moving particles around
_particleAnimationSet.addAnimation(particleFollowNode);
//then BillBoad stopped working...
_particleAnimationSet.addAnimation(new ParticleBillboardNode());
_particleAnimationSet.initParticleFunc = initFunc;
I've fixed the bug. the particle mesh's bounds doesn't update properly which cause the mesh culling step cut it off while the mesh's fake bounds isn't in camera's frustum .
How to fix:
1. Set particle mesh's id as "Particles"
2. In MeshNode.cs file, function acceptTraverser, modify as :
override public function acceptTraverser(traverser:PartitionTraverser):void
{
//trace(_mesh.id);
if (traverser.enterNode(this)||_mesh.id=="Particles")
{
super.acceptTraverser(traverser);
var subs:Vector.<SubMesh> = _mesh.subMeshes;
var i:uint;
var len:uint = subs.length;
while (i < len)
traverser.applyRenderable(subs[i++]);
}
}