int Building (float width, float length, float height, float posx, float posy, SCNScene scene, Random rnd) { var boxNode = new SCNNode () { Geometry = new SCNBox { Width = width, Height = height, Length = length, ChamferRadius = 0.02f }, Position = new SCNVector3(posx, height/2.0f, posy) }; scene.RootNode.AddChildNode (boxNode); var buildings = new[] { "Content/building1.jpg", "Content/building2.jpg","Content/building3.jpg" }; var material = new SCNMaterial (); material.Diffuse.Contents = UIImage.FromFile (buildings [rnd.Next (buildings.Length)]); material.Diffuse.ContentsTransform = SCNMatrix4.Scale (new SCNVector3 (width, height, 1.0f)); material.Diffuse.WrapS = SCNWrapMode.Repeat; material.Diffuse.WrapT = SCNWrapMode.Repeat; material.Diffuse.MipFilter = SCNFilterMode.Linear; material.Diffuse.MagnificationFilter = SCNFilterMode.Linear; material.Specular.Contents = UIColor.Gray; material.LocksAmbientWithDiffuse = true; boxNode.Geometry.FirstMaterial = material; return 0; }
public override void SetupSlide (PresentationViewController presentationViewController) { // Set the slide's title and subtitle and add some text TextManager.SetTitle ("Animations"); TextManager.SetSubtitle ("Implicit animations"); TextManager.AddCode ("#// Begin a transaction \n" + "#SCNTransaction#.Begin (); \n" + "#SCNTransaction#.AnimationDuration = 2.0f; \n\n" + "// Change properties \n" + "aNode.#Opacity# = 1.0f; \n" + "aNode.#Rotation# = \n" + " new SCNVector4 (0, 1, 0, NMath.PI * 4); \n\n" + "// Commit the transaction \n" + "SCNTransaction.#Commit ()#;#"); // A simple torus that we will animate to illustrate the code AnimatedNode = SCNNode.Create (); AnimatedNode.Position = new SCNVector3 (10, 7, 0); // Use an extra node that we can tilt it and cumulate that with the animation var torusNode = SCNNode.Create (); torusNode.Geometry = SCNTorus.Create (4.0f, 1.5f); torusNode.Rotation = new SCNVector4 (1, 0, 0, -(float)(Math.PI * 0.7f)); torusNode.Geometry.FirstMaterial.Diffuse.Contents = NSColor.Red; torusNode.Geometry.FirstMaterial.Specular.Contents = NSColor.White; torusNode.Geometry.FirstMaterial.Reflective.Contents = new NSImage (NSBundle.MainBundle.PathForResource ("SharedTextures/envmap", "jpg")); torusNode.Geometry.FirstMaterial.FresnelExponent = 0.7f; AnimatedNode.AddChildNode (torusNode); ContentNode.AddChildNode (AnimatedNode); }
public override void SetupSlide (PresentationViewController presentationViewController) { // Load the scene var intermediateNode = SCNNode.Create (); intermediateNode.Position = new SCNVector3 (6, 9, 0); intermediateNode.Scale = new SCNVector3 (1.4f, 1, 1); GroundNode.AddChildNode (intermediateNode); MapNode = Utils.SCAddChildNode (intermediateNode, "Map", "Scenes/map/foldingMap", 25); MapNode.Position = new SCNVector3 (0, 0, 0); MapNode.Opacity = 0.0f; // Use a bunch of shader modifiers to simulate ambient occlusion when the map is folded var geomFile = NSBundle.MainBundle.PathForResource ("Shaders/mapGeometry", "shader"); var fragFile = NSBundle.MainBundle.PathForResource ("Shaders/mapFragment", "shader"); var lightFile = NSBundle.MainBundle.PathForResource ("Shaders/mapLighting", "shader"); var geometryModifier = File.ReadAllText (geomFile); var fragmentModifier = File.ReadAllText (fragFile); var lightingModifier = File.ReadAllText (lightFile); MapNode.Geometry.ShaderModifiers = new SCNShaderModifiers { EntryPointGeometry = geometryModifier, EntryPointFragment = fragmentModifier, EntryPointLightingModel = lightingModifier }; }
public override void SetupSlide (PresentationViewController presentationViewController) { // Create a node to own the "sign" model, make it to be close to the camera, rotate by 90 degree because it's oriented with z as the up axis var intermediateNode = SCNNode.Create (); intermediateNode.Position = new SCNVector3 (0, 0, 7); intermediateNode.Rotation = new SCNVector4 (1, 0, 0, -(float)(Math.PI / 2)); GroundNode.AddChildNode (intermediateNode); // Load the "sign" model var signNode = Utils.SCAddChildNode (intermediateNode, "sign", "Scenes/intersection/intersection", 30); signNode.Position = new SCNVector3 (4, -2, 0.05f); // Re-parent every node that holds a camera otherwise they would inherit the scale from the "sign" model. // This is not a problem except that the scale affects the zRange of cameras and so it would be harder to get the transition from one camera to another right var cameraNodes = new NSMutableArray (); foreach (SCNNode child in signNode) { if (child.Camera != null) cameraNodes.Add (child); } for (nuint i = 0; i < cameraNodes.Count; i++) { var cameraNode = new SCNNode (cameraNodes.ValueAt ((uint)i)); var previousWorldTransform = cameraNode.WorldTransform; intermediateNode.AddChildNode (cameraNode); // re-parent cameraNode.Transform = intermediateNode.ConvertTransformFromNode (previousWorldTransform, null); cameraNode.Scale = new SCNVector3 (1, 1, 1); } }
public override void SetupSlide (PresentationViewController presentationViewController) { // Add some text TextManager.SetTitle ("Loading a 3D Scene"); TextManager.SetSubtitle ("DAE Documents"); NodesToDim = new List <SCNNode> (); TextManager.AddBulletAtLevel ("Geometries", 0); TextManager.AddBulletAtLevel ("Animations", 0); NodesToDim.Add (TextManager.AddBulletAtLevel ("Textures", 0)); NodesToDim.Add (TextManager.AddBulletAtLevel ("Lighting", 0)); NodesToDim.Add (TextManager.AddBulletAtLevel ("Cameras", 0)); NodesToDim.Add (TextManager.AddBulletAtLevel ("Skinning", 0)); NodesToDim.Add (TextManager.AddBulletAtLevel ("Morphing", 0)); // And an image resting on the ground DaeIcon = Utils.SCPlaneNode (NSBundle.MainBundle.PathForResource ("Images/dae file icon", "png"), 10, false); DaeIcon.Position = new SCNVector3 (6, 4.5f, 1); GroundNode.AddChildNode (DaeIcon); AbcIcon = Utils.SCPlaneNode (NSBundle.MainBundle.PathForResource ("Images/abc file icon", "png"), 10, false); AbcIcon.Position = new SCNVector3 (6, 4.5f, 30); GroundNode.AddChildNode (AbcIcon); }
public override void SetupSlide (PresentationViewController presentationViewController) { // Load the character and add it to the scene var heroNode = Utils.SCAddChildNode (GroundNode, "heroGroup", "Scenes/hero/hero", 0.0f); heroNode.Scale = new SCNVector3 (0.023f, 0.023f, 0.023f); heroNode.Position = new SCNVector3 (0.0f, 0.0f, 15.0f); heroNode.Rotation = new SCNVector4 (1.0f, 0.0f, 0.0f, -(float)(Math.PI / 2)); GroundNode.AddChildNode (heroNode); // Convert sceneTime-based animations into systemTime-based animations. // Animations loaded from DAE files will play according to the `currentTime` property of the scene renderer if this one is playing // (see the SCNSceneRenderer protocol). Here we don't play a specific DAE so we want the animations to animate as soon as we add // them to the scene (i.e have them to play according the time of the system when the animation was added). HeroSkeletonNode = heroNode.FindChildNode ("skeleton", true); foreach (var animationKey in HeroSkeletonNode.GetAnimationKeys ()) { // Find all the animations. Make them system time based and repeat forever. // And finally replace the old animation. var animation = HeroSkeletonNode.GetAnimation (animationKey); animation.UsesSceneTimeBase = false; animation.RepeatCount = float.MaxValue; HeroSkeletonNode.AddAnimation (animation, animationKey); } // Load other animations so that we will use them later SetAnimation (CharacterAnimation.Attack, "attackID", "attack"); SetAnimation (CharacterAnimation.Die, "DeathID", "death"); SetAnimation (CharacterAnimation.Walk, "WalkID", "walk"); }
// Queries the root node for the expected nodes. internal GameNodes (SCNNode sceneRoot) { Object = sceneRoot.FindChildNode ("teapot", true); if (Object == null) throw new InvalidProgramException (); ObjectMaterial = Object.Geometry?.FirstMaterial; if (ObjectMaterial == null) throw new InvalidProgramException (); Confetti = sceneRoot.FindChildNode ("particles", true); if (Confetti == null) throw new InvalidProgramException (); Camera = sceneRoot.FindChildNode ("camera", true).Camera; if (Camera == null) throw new InvalidProgramException (); CountdownLabel = new SKLabelNode ("Chalkduster") { HorizontalAlignmentMode = SKLabelHorizontalAlignmentMode.Center }; CongratulationsLabel = new SKLabelNode ("Chalkduster") { FontColor = GameColors.DefaultFont, Text = "You Win!", FontSize = 45 }; }
public override void SetupSlide (PresentationViewController presentationViewController) { // Set the slide's title and subtitle and add some text TextManager.SetTitle ("Animations"); TextManager.SetSubtitle ("Explicit animations"); TextManager.AddCode ("#// Create an animation \n" + "animation = #CABasicAnimation#.FromKeyPath (\"rotation\"); \n\n" + "// Configure the animation \n" + "animation.#Duration# = 2.0f; \n" + "animation.#To# = NSValue.FromVector (new SCNVector4 (0, 1, 0, NMath.PI * 2)); \n" + "animation.#RepeatCount# = float.MaxValue; \n\n" + "// Play the animation \n" + "aNode.#AddAnimation #(animation, \"myAnimation\");#"); // A simple torus that we will animate to illustrate the code AnimatedNode = SCNNode.Create (); AnimatedNode.Position = new SCNVector3 (9, 5.7f, 16); // Use an extra node that we can tilt it and cumulate that with the animation var torusNode = SCNNode.Create (); torusNode.Geometry = SCNTorus.Create (4.0f, 1.5f); torusNode.Rotation = new SCNVector4 (1, 0, 0, -(float)(Math.PI * 0.5f)); torusNode.Geometry.FirstMaterial.Diffuse.Contents = NSColor.Cyan; torusNode.Geometry.FirstMaterial.Specular.Contents = NSColor.White; torusNode.Geometry.FirstMaterial.Reflective.Contents = new NSImage (NSBundle.MainBundle.PathForResource ("SharedTextures/envmap", "jpg")); torusNode.Geometry.FirstMaterial.FresnelExponent = 0.7f; AnimatedNode.AddChildNode (torusNode); ContentNode.AddChildNode (AnimatedNode); }
void SetupCamera () { SCNNode pov = GameView.PointOfView; const float altitude = 1f; const float distance = 10f; cameraYHandle = SCNNode.Create (); cameraXHandle = SCNNode.Create (); cameraYHandle.Position = new SCNVector3 (0f, altitude, 0f); cameraYHandle.AddChildNode (cameraXHandle); GameView.Scene.RootNode.AddChildNode (cameraYHandle); pov.EulerAngles = new SCNVector3 (0f, 0f, 0f); pov.Position = new SCNVector3 (0f, 0f, distance); cameraYHandle.Rotation = new SCNVector4 (0f, 1f, 0f, (float)Math.PI / 2f + (float)Math.PI / 4f * 3f); cameraXHandle.Rotation = new SCNVector4 (1f, 0f, 0f, -(float)Math.PI / 4f * 0.125f); cameraXHandle.AddChildNode (pov); // Animate camera on launch and prevent the user from manipulating the camera until the end of the animation lockCamera = true; SCNTransaction.Begin (); SCNTransaction.SetCompletionBlock (() => { lockCamera = false; }); var cameraYAnimation = CABasicAnimation.FromKeyPath ("rotation.w"); cameraYAnimation.From = NSNumber.FromDouble (Math.PI * 2 - cameraYHandle.Rotation.W); cameraYAnimation.To = NSNumber.FromDouble (0.0); cameraYAnimation.Additive = true; cameraYAnimation.BeginTime = CAAnimation.CurrentMediaTime () + 3; cameraYAnimation.FillMode = CAFillMode.Both; cameraYAnimation.Duration = 5.0; cameraYAnimation.TimingFunction = CAMediaTimingFunction.FromName (CAMediaTimingFunction.EaseInEaseOut); cameraYHandle.AddAnimation (cameraYAnimation, null); var cameraXAnimation = CABasicAnimation.FromKeyPath ("rotation.w"); cameraXAnimation.From = NSNumber.FromDouble (-Math.PI / 2 + cameraXHandle.Rotation.W); cameraXAnimation.To = NSNumber.FromDouble (0.0); cameraXAnimation.Additive = true; cameraXAnimation.FillMode = CAFillMode.Both; cameraXAnimation.Duration = 5.0; cameraXAnimation.BeginTime = CAAnimation.CurrentMediaTime () + 3; cameraXAnimation.TimingFunction = CAMediaTimingFunction.FromName (CAMediaTimingFunction.EaseInEaseOut); cameraXHandle.AddAnimation (cameraXAnimation, null); SCNTransaction.Commit (); var lookAtConstraint = SCNLookAtConstraint.Create (Character.Node.FindChildNode ("Bip001_Head", true)); lookAtConstraint.InfluenceFactor = 0; pov.Constraints = new SCNConstraint[] { lookAtConstraint }; }
public override void PresentStep (int index, PresentationViewController presentationViewController) { SCNTransaction.Begin (); SCNTransaction.AnimationDuration = 0; switch (index) { case 0: // Set the slide's title and subtile and add some text TextManager.SetTitle ("Node Attributes"); TextManager.SetSubtitle ("Lights"); TextManager.AddBulletAtLevel ("SCNLight", 0); TextManager.AddBulletAtLevel ("Four light types", 0); TextManager.AddBulletAtLevel ("Omni", 1); TextManager.AddBulletAtLevel ("Directional", 1); TextManager.AddBulletAtLevel ("Spot", 1); TextManager.AddBulletAtLevel ("Ambient", 1); break; case 1: // Add some code var codeExampleNode = TextManager.AddCode ("#aNode.#Light# = SCNLight.Create (); \naNode.Light.LightType = SCNLightType.Omni;#"); codeExampleNode.Position = new SCNVector3 (14, 11, 1); // Add a light to the scene LightNode = SCNNode.Create (); LightNode.Light = SCNLight.Create (); LightNode.Light.LightType = SCNLightType.Omni; LightNode.Light.Color = NSColor.Black; // initially off LightNode.Light.SetAttribute (new NSNumber (30), SCNLightAttribute.AttenuationStartKey); LightNode.Light.SetAttribute (new NSNumber (40), SCNLightAttribute.AttenuationEndKey); LightNode.Position = new SCNVector3 (5, 3.5f, 0); ContentNode.AddChildNode (LightNode); // Load two images to help visualize the light (on and off) LightOffImageNode = Utils.SCPlaneNode (NSBundle.MainBundle.PathForResource ("Images/light-off", "tiff"), 7, false); LightOnImageNode = Utils.SCPlaneNode (NSBundle.MainBundle.PathForResource ("Images/light-on", "tiff"), 7, false); LightOnImageNode.Opacity = 0; LightNode.AddChildNode (LightOnImageNode); LightNode.AddChildNode (LightOffImageNode); break; case 2: // Switch the light on SCNTransaction.Begin (); SCNTransaction.AnimationDuration = 1; LightNode.Light.Color = NSColor.FromCalibratedRgba (1, 1, 0.8f, 1); LightOnImageNode.Opacity = 1.0f; LightOffImageNode.Opacity = 0.0f; SCNTransaction.Commit (); break; } SCNTransaction.Commit (); }
public override void SetupSlide (PresentationViewController presentationViewController) { RedColor = NSColor.FromDeviceRgba (168.0f / 255.0f, 21.0f / 255.0f, 0.0f / 255.0f, 1); GreenColor = NSColor.FromDeviceRgba (154.0f / 255.0f, 197.0f / 255.0f, 58.0f / 255.0f, 1); BlueColor = NSColor.FromDeviceRgba (49.0f / 255.0f, 80.0f / 255.0f, 201.0f / 255.0f, 1); PurpleColor = NSColor.FromDeviceRgba (190.0f / 255.0f, 56.0f / 255.0f, 243.0f / 255.0f, 1); // Create the diagram but hide it DiagramNode = CloningDiagramNode (); DiagramNode.Opacity = 0.0f; ContentNode.AddChildNode (DiagramNode); }
public LineNode() { var line = (SCNGeometry)template.Copy(NSZone.Default); line.FirstMaterial = GetNativeMaterial(style.Color); lineNode = SCNNode.FromGeometry(line); var cap = (SCNGeometry)capTemplate.Copy(NSZone.Default); cap.FirstMaterial = line.FirstMaterial; scapNode = SCNNode.FromGeometry(cap); ecapNode = SCNNode.FromGeometry(cap); AddChildNode(lineNode); AddChildNode(scapNode); AddChildNode(ecapNode); }
public GameSimulation() { // We create one level in our simulation. GameLevel = new GameLevel(); CurrentGameState = GameState.Paused; // Register ourself as a listener to physics callbacks. SCNNode levelNode = GameLevel.CreateLevel(); RootNode.AddChildNode(levelNode); PhysicsWorld.WeakContactDelegate = this; PhysicsWorld.Gravity = new SCNVector3(0f, -800f, 0f); SetupTechniques(); }
void SetupMusic() { // Get an arbitrary node to attach the sounds to. SCNNode node = GameView.Scene.RootNode; SCNAudioSource source = SCNAudioSource.FromFile("game.scnassets/sounds/music.m4a"); source.Loops = true; source.Volume = 0.25f; source.ShouldStream = true; source.Positional = false; SCNAudioPlayer player = SCNAudioPlayer.FromSource(source); node.AddAudioPlayer(player); }
public void CreateAnimations () { Name = "monkey"; rightHand = FindChildNode ("Bone_R_Hand", true); isIdle = true; hasCoconut = false; SetupTauntAnimation (); SetupHangAnimation (); SetupGetCoconutAnimation (); SetupThrowAnimation (); ChainAnimation ("monkey_get_coconut-1", "monkey_throw_coconut-1"); mainSkeleton.AddAnimation (CachedAnimationForKey ("monkey_tree_hang-1"), "monkey_idle"); }
public static SCNNode ParentWithPrefix(this SCNNode node, string prefix) { SCNNode result = null; if (!string.IsNullOrEmpty(node.Name) && node.Name.StartsWith(prefix, StringComparison.Ordinal)) { result = node; } else if (node.ParentNode != null) { result = node.ParentNode.ParentWithPrefix(prefix); } return(result); }
public void DidAddNode(ISCNSceneRenderer renderer, SCNNode node, ARAnchor anchor) { if (anchor.Name != virtualObjectAnchorName) { return; } // save the reference to the virtual object anchor when the anchor is added from relocalizing if (objAnchor == null) { objAnchor = anchor; } node.AddChildNode(VirtualObject); }
private SCNNode CreateBlock(SCNVector3 position, SCNVector3 size) { if (DiceMesh == null) { DiceMesh = CreateBlockMesh(size); } var model = SCNNode.Create(); model.Position = position; model.Geometry = DiceMesh; model.PhysicsBody = SCNPhysicsBody.CreateDynamicBody(); return(model); }
public static void StopAllAnimations(this SCNNode node) { node.EnumerateChildNodes((SCNNode child, out bool stop) => { stop = false; foreach (var key in child.GetAnimationKeys()) { var animationPlayer = child.GetAnimationPlayer(key); if (animationPlayer != null) { animationPlayer.Stop(); } } }); }
public void AddAnimation() { TestRuntime.AssertSystemVersion(PlatformName.iOS, 8, 0, throwIfOtherPlatform: false); TestRuntime.AssertSystemVersion(PlatformName.MacOSX, 10, 8, throwIfOtherPlatform: false); using (var a = CAAnimation.CreateAnimation()) using (var n = SCNNode.Create()) { n.AddAnimation(a, (NSString)null); n.AddAnimation(a, (string)null); string key = "key"; n.AddAnimation(a, key); using (var s = new NSString(key)) n.AddAnimation(a, s); } }
public ResetSwitchComponent(GameObject entity, SCNNode lever) : base() { this.Base = entity.ObjectRootNode; this.leverObj = lever; // find outline node to mirror highlighting var highlightNode = entity.ObjectRootNode.FindChildNode("Highlight", true); var mirrorOutline = highlightNode.FindChildNode("resetSwitch_leverOutline", true); if (highlightNode != null && mirrorOutline != null) { this.highlightObj = highlightNode; this.mirrorObj = mirrorOutline; } }
void HandleRotateGesture(UIRotationGestureRecognizer sender) { SCNView areaPanned = sender.View as SCNView; CGPoint point = sender.LocationInView(areaPanned); SCNHitTestResult[] hitResults = areaPanned.HitTest(point, new SCNHitTestOptions()); SCNHitTestResult hit = hitResults.FirstOrDefault(); if (hit != null) { SCNNode node = hit.Node; zAngle += (float)(-sender.Rotation); node.EulerAngles = new SCNVector3(node.EulerAngles.X, node.EulerAngles.Y, zAngle); } }
public void SCNNode_AddAnimation() { SCNNode c = new SCNNode(); CABasicAnimation a = CABasicAnimation.FromKeyPath("hidden"); NSString key = new NSString("MyKey"); c.AddAnimation(a, key); CAPropertyAnimation cur = (CAPropertyAnimation)c.GetAnimation(key); Assert.IsNotNull(cur); Assert.AreEqual(cur.KeyPath, "hidden"); c.RemoveAnimation(key); cur = (CAPropertyAnimation)c.GetAnimation(key); Assert.IsNull(cur); }
void SetupSounds() { // Get an arbitrary node to attach the sounds to SCNNode node = GameView.Scene.RootNode; // The wind sound SCNAudioSource source = SCNAudioSource.FromFile("game.scnassets/sounds/wind.m4a"); source.Volume = .3f; SCNAudioPlayer player = SCNAudioPlayer.FromSource(source); source.Loops = true; source.ShouldStream = true; source.Positional = false; node.AddAudioPlayer(player); // fire source = SCNAudioSource.FromFile("game.scnassets/sounds/flamethrower.mp3"); source.Loops = true; source.Volume = 0; source.Positional = false; flameThrowerSound = SCNAudioPlayer.FromSource(source); node.AddAudioPlayer(flameThrowerSound); // hit hitSound = SCNAudioSource.FromFile("game.scnassets/sounds/ouch_firehit.mp3"); hitSound.Volume = 2f; hitSound.Load(); pshhhSound = SCNAudioSource.FromFile("game.scnassets/sounds/fire_extinction.mp3"); pshhhSound.Volume = 2f; pshhhSound.Load(); aahSound = SCNAudioSource.FromFile("game.scnassets/sounds/aah_extinction.mp3"); aahSound.Volume = 2f; aahSound.Load(); // collectable collectPearlSound = SCNAudioSource.FromFile("game.scnassets/sounds/collect1.mp3"); collectPearlSound.Volume = 0.5f; collectPearlSound.Load(); collectFlowerSound = SCNAudioSource.FromFile("game.scnassets/sounds/collect1.mp3"); collectFlowerSound.Load(); // victory victoryMusic = SCNAudioSource.FromFile("game.scnassets/sounds/Music_victory.mp3"); victoryMusic.Volume = 0.5f; }
/// <summary> /// this is what is called if custom collision response is active /// </summary> public void DidCollision(GameManager manager, SCNNode node, SCNNode otherNode, SCNVector3 pos, float impulse) { // we don't play sound if this is a triggerVolume if (!string.IsNullOrEmpty(node.Name) && node.Name.StartsWith("CollisionTrigger", StringComparison.Ordinal)) { return; } if (!string.IsNullOrEmpty(otherNode.Name) && otherNode.Name.StartsWith("CollisionTrigger", StringComparison.Ordinal)) { return; } var names = new string[] { node.Name, otherNode.Name }; var withBall = names.Contains("ball"); var withTable = names.Contains("OcclusionBox"); if (node.Name == "OcclusionBox") { // don't play any sounds on the table. return; } var effectiveImpulse = impulse; if (withTable) { // the table does not move, so the calculated impulse is zero (sometimes?). // Ensure that the ball has an impulse value, so if it happens to be zero, // fake one based on its velocity if (impulse == 0f && withBall) { if (node.PhysicsBody != null) { var v = node.PhysicsBody.Velocity; var factor = 1.5f; var velocity = new SCNVector3(v.X, v.Y, v.Z).Length; effectiveImpulse = factor * velocity; } else { effectiveImpulse = 0; } } } this.PrepareCollisionSound(effectiveImpulse, withBall, withTable); }
public override void OnFrameUpdate(ARSession session, ARFrame frame) { base.OnFrameUpdate(session, frame); if (adding) { return; } var results = SCNView.HitTest(View.Center, new SCNHitTestOptions { SortResults = true, BackFaceCulling = false, SearchMode = SCNHitTestSearchMode.All, FirstFoundOnly = false }); SCNNode newNode = null; var match = results.FirstOrDefault(r => NodeLookup.ContainsKey(r.Node)); if (match != null) { newNode = match.Node; } var changed = newNode != SelectedNode; var oldNode = SelectedNode; SelectedNode = newNode; if (changed) { var panelTransform = SelectedNode != null ? CGAffineTransform.MakeIdentity() : CGAffineTransform.MakeTranslation(0, 1000); if (SelectedNode != null) { var content = _contentFor[NodeLookup[match.Node].Name]; InfoDialog.Label.Text = content.Description; TitleDialog.Label.Text = content.Name; } UIView.Animate(.2, 0, UIViewAnimationOptions.CurveEaseOut, () => { InfoDialog.View.Transform = panelTransform; TitleDialog.View.Transform = panelTransform; }, null); } }
public override void SetupSlide(PresentationViewController presentationViewController) { TextManager.SetTitle("Depth of Field"); TextManager.SetSubtitle("SCNCamera"); // Create a node that will contain the chess board var intermediateNode = SCNNode.Create(); intermediateNode.Scale = new SCNVector3(35.0f, 35.0f, 35.0f); intermediateNode.Position = new SCNVector3(0, 2.1f, 20); intermediateNode.Rotation = new SCNVector4(1, 0, 0, -(float)(Math.PI / 2)); ContentNode.AddChildNode(intermediateNode); // Load the chess model and add to "intermediateNode" Utils.SCAddChildNode(intermediateNode, "Line01", "Scenes.scnassets/chess/chess", 1); }
/// <summary> /// Creates a plane an place in on the center of the plane anchor /// and rotates so it lies flat /// </summary> private void PlaceAnchorNode(SCNNode node, ARPlaneAnchor anchor) { var plane = SCNPlane.Create(anchor.Extent.X, anchor.Extent.Z); var material = new SCNMaterial(); material.Diffuse.Contents = UIImage.FromFile("art.scnassets/PlaneGrid/grid.png"); plane.Materials = new[] { material }; plane.FirstMaterial.Transparency = 0.1f; var planeNode = SCNNode.FromGeometry(plane); planeNode.Position = new SCNVector3(anchor.Center.X, 0.0f, anchor.Center.Z); planeNode.Transform = SCNMatrix4.CreateRotationX((float)(-Math.PI / 2.0)); node.AddChildNode(planeNode); }
public static void AddRotationAction(this SCNNode node, SCNActionTimingMode mode, double secs, bool loop = false) { SCNAction rotateAction = SCNAction.RotateBy(0, (float)Math.PI, 0, secs); rotateAction.TimingMode = mode; if (loop) { SCNAction indefiniteRotation = SCNAction.RepeatActionForever(rotateAction); node.RunAction(indefiniteRotation, "rotation"); } else { node.RunAction(rotateAction, "rotation"); } }
private async Task AnimateNode(SCNNode node) { var sourcePosition = new SCNVector3(node.PresentationNode.Position.X, node.PresentationNode.Position.Y, node.PresentationNode.Position.Z); var targetPosition = new SCNVector3(node.PresentationNode.Position.X - 0.2f, node.PresentationNode.Position.Y - 0.2f, node.PresentationNode.Position.Z - 0.2f); for (int i = 0; i < 3; i++) { SCNAction toTarget = SCNAction.MoveTo(targetPosition, 0.2f); node.RunAction(toTarget); await Task.Delay(200); SCNAction toSource = SCNAction.MoveTo(sourcePosition, 0.2f); node.RunAction(toSource); await Task.Delay(200); } }
private SCNNode CreateTrackNode() { var geometry = new SCNPlane() { Width = this.Width, Height = this.Length }; var trackNode = new SCNNode(); trackNode.Geometry = geometry; trackNode.Geometry.Materials.First().Diffuse.Contents = TRACK_COLOR; trackNode.EulerAngles = new SCNVector3(-1 * (float)Math.PI / 2, (float)Math.PI / 2, 0); trackNode.Position = new SCNVector3(0f, 0f, 0f); return(trackNode); }
public PlaneNode(int number, nfloat width, nfloat length, SCNVector3 position, string imagePath) { var rootNode = new SCNNode { Geometry = CreateGeometry(width, length, imagePath), Position = position, }; Opacity = 0; Number = number; AddChildNode(rootNode); }
public static void SetNodeToOccluder(this SCNNode node) { var material = SCNMaterialExtensions.Create(UIColor.White); material.ColorBufferWriteMask = SCNColorMask.None; material.WritesToDepthBuffer = true; if (node.Geometry == null) { throw new Exception("Node has no geometry"); } node.Geometry.Materials = new SCNMaterial[] { material }; node.RenderingOrder = -10; node.CastsShadow = false; }
public void SCNNode_SetPhysicsBodyTest() { Asserts.EnsureYosemite(); if (IntPtr.Size == 8) { // Create a new empty scene var Scene = new SCNScene(); var floorNode = SCNNode.Create(); Scene.RootNode.AddChildNode(floorNode); floorNode.PhysicsBody = SCNPhysicsBody.CreateStaticBody(); Scene.PhysicsWorld.Speed = 0; } }
void SetupAutomaticCameraPositions() { SCNNode root = GameView.Scene.RootNode; mainGround = root.FindChildNode("bloc05_collisionMesh_02", true); groundToCameraPosition = new Dictionary <SCNNode, SCNVector3> (); groundToCameraPosition.Add(root.FindChildNode("bloc04_collisionMesh_02", true), new SCNVector3(-0.188683f, 4.719608f, 0f)); groundToCameraPosition.Add(root.FindChildNode("bloc03_collisionMesh", true), new SCNVector3(-0.435909f, 6.297167f, 0f)); groundToCameraPosition.Add(root.FindChildNode("bloc07_collisionMesh", true), new SCNVector3(-0.333663f, 7.868592f, 0f)); groundToCameraPosition.Add(root.FindChildNode("bloc08_collisionMesh", true), new SCNVector3(-0.575011f, 8.739003f, 0f)); groundToCameraPosition.Add(root.FindChildNode("bloc06_collisionMesh", true), new SCNVector3(-1.095519f, 9.425292f, 0f)); groundToCameraPosition.Add(root.FindChildNode("bloc05_collisionMesh_02", true), new SCNVector3(-0.072051f, 8.202264f, 0f)); groundToCameraPosition.Add(root.FindChildNode("bloc05_collisionMesh_01", true), new SCNVector3(-0.072051f, 8.202264f, 0)); }
public override void OnNodeAddedForAnchor(ISCNSceneRenderer renderer, SCNNode node, ARAnchor anchor) { if (!(anchor is ARPlaneAnchor planeAnchor)) { return; } var color = planeAnchor.Alignment == ARPlaneAnchorAlignment.Horizontal ? UIColor.Blue : UIColor.Red; var planeNode = CreateARPlaneNode(planeAnchor, color.ColorWithAlpha(.5f)); node.AddChildNode(planeNode); Planes.Add(planeNode); }
private void AddPrimitive(SCNGeometry geometry, float yPos, CABasicAnimation rotationAnimation, SCNMaterial sharedMaterial) { var xPos = 13.0f * (float)Math.Sin((float)Math.PI * 2 * PrimitiveIndex / 9.0f); var zPos = 13.0f * (float)Math.Cos((float)Math.PI * 2 * PrimitiveIndex / 9.0f); var node = SCNNode.Create(); node.Position = new SCNVector3(xPos, yPos, zPos); node.Geometry = geometry; node.Geometry.FirstMaterial = sharedMaterial; CarouselNode.AddChildNode(node); PrimitiveIndex++; rotationAnimation.TimeOffset = -PrimitiveIndex; node.AddAnimation(rotationAnimation, new NSString("rotationAnimation")); }
public override void OnSessionBegan() { var b = SCNScene.FromFile("art.scnassets/basic-prefab.scn") .RootNode .ChildNodes .First(x => x.Name.StartsWith("char", StringComparison.Ordinal)); PaintNode = b.Clone(); PaintNode.RemoveFromParentNode(); PaintNode.Position = new SCNVector3(0, 0, -1.5f); PaintNode.Opacity = 0.75f; SCNView.PointOfView.AddChildNode(PaintNode); base.OnSessionBegan(); }
public void CollectBanana(SCNNode banana) { // Flyoff the banana to the screen space position score label. // Don't increment score until the banana hits the score label. // ignore collisions banana.PhysicsBody = null; BananasCollected++; int variance = 60; nfloat duration = 0.25f; nfloat apexY = worldSpaceLabelScorePosition.Y * 0.8f + (new Random().Next(0, variance) - variance / 2); worldSpaceLabelScorePosition.Z = banana.Position.Z; var apex = new SCNVector3(banana.Position.X + 10 + (new Random().Next(0, variance) - variance / 2), apexY, banana.Position.Z); SCNAction startFlyOff = SCNAction.MoveTo(apex, duration); startFlyOff.TimingMode = SCNActionTimingMode.EaseOut; SCNAction endFlyOff = SCNAction.CustomAction(duration, new SCNActionNodeWithElapsedTimeHandler((node, elapsedTime) => { nfloat t = elapsedTime / duration; var v = new SCNVector3( apex.X + ((worldSpaceLabelScorePosition.X - apex.X) * t), apex.Y + ((worldSpaceLabelScorePosition.Y - apex.Y) * t), apex.X + ((worldSpaceLabelScorePosition.Z - apex.Z) * t)); node.Position = v; })); endFlyOff.TimingMode = SCNActionTimingMode.EaseInEaseOut; SCNAction flyoffSequence = SCNAction.Sequence(new SCNAction[] { startFlyOff, endFlyOff }); banana.RunAction(flyoffSequence, () => { Bananas.Remove(banana); banana.RemoveFromParentNode(); // Add to score. Score++; GameSimulation.Sim.PlaySound("deposit.caf"); // Game Over if (Bananas.Count == 0) { DoGameOver(); } }); }
public override void SetupSlide (PresentationViewController presentationViewController) { TextManager.SetTitle ("Scene Manipulation"); TextManager.SetSubtitle ("Retrieving a node"); TextManager.AddCode ("#// Get by name \n" + "var aNode = scene.RootNode \n" + " .#FindChildNode #(\"aName\", true);#"); sceneGraphDiagramNode = SlideSceneGraph.SharedScenegraphDiagramNode (); SlideSceneGraph.ScenegraphDiagramGoToStep (7); sceneGraphDiagramNode.Opacity = 0.0f; sceneGraphDiagramNode.Position = new SCNVector3 (1.5f, 8.0f, 0); ContentNode.AddChildNode (sceneGraphDiagramNode); }
public static SCNNode SCPlaneNodeWithImage(NSImage image, nfloat size, bool isLit) { var node = SCNNode.Create(); var factor = size / (nfloat)(Math.Max(image.Size.Width, image.Size.Height)); node.Geometry = SCNPlane.Create(image.Size.Width * factor, image.Size.Height * factor); node.Geometry.FirstMaterial.Diffuse.Contents = image; //if we don't want the image to be lit, set the lighting model to "constant" if (!isLit) { node.Geometry.FirstMaterial.LightingModelName = SCNLightingModel.Constant; } return(node); }
private SCNScene SetupScene() { var scene = SCNScene.Create(); SetupInvironment(scene); SetupSceneElements(scene); vehicleNode = SetupVehicle(scene); cameraNode = SCNNode.Create(); cameraNode.Camera = SCNCamera.Create(); cameraNode.Camera.ZFar = 500f; cameraNode.Position = new SCNVector3(0f, 60f, 50f); cameraNode.Rotation = new SCNVector4(1f, 0f, 0f, -(float)Math.PI / 4f * 0.75f); scene.RootNode.AddChildNode(cameraNode); return(scene); }
private void LoadCharacter() { // Load character from external file var scene = SCNScene.FromFile("art.scnassets/character/max.scn"); this.model = scene.RootNode.FindChildNode("Max_rootNode", true); this.model.Position = Character.ModelOffset; /* setup character hierarchy * character |_orientationNode |_model */ this.characterNode = new SCNNode { Name = "character", Position = Character.InitialPosition }; this.characterOrientation = new SCNNode(); this.characterNode.AddChildNode(this.characterOrientation); this.characterOrientation.AddChildNode(this.model); var collider = this.model.FindChildNode("collider", true); if (collider?.PhysicsBody != null) { collider.PhysicsBody.CollisionBitMask = (int)(Bitmask.Enemy | Bitmask.Trigger | Bitmask.Collectable); } // Setup collision shape var min = new SCNVector3(); var max = new SCNVector3(); this.model.GetBoundingBox(ref min, ref max); nfloat collisionCapsuleRadius = (max.X - min.X) * 0.4f; nfloat collisionCapsuleHeight = max.Y - min.Y; var collisionGeometry = SCNCapsule.Create(collisionCapsuleRadius, collisionCapsuleHeight); this.characterCollisionShape = SCNPhysicsShape.Create(collisionGeometry, new NSMutableDictionary() { { SCNPhysicsShapeOptionsKeys.CollisionMargin, NSNumber.FromFloat(Character.CollisionMargin) } }); this.collisionShapeOffsetFromModel = new SCNVector3(0f, (float)collisionCapsuleHeight * 0.51f, 0f); }
public override void SetupSlide (PresentationViewController presentationViewController) { TextManager.SetTitle ("Materials"); TextManager.AddBulletAtLevel ("Determines the appearance of the geometry", 0); TextManager.AddBulletAtLevel ("SCNMaterial", 0); TextManager.AddBulletAtLevel ("Material properties", 0); TextManager.AddBulletAtLevel ("SCNMaterialProperty", 1); TextManager.AddBulletAtLevel ("Contents is a color or an image", 1); // Prepare the diagram but hide it for now SceneGraphDiagramNode = SlideSceneGraph.SharedScenegraphDiagramNode (); SlideSceneGraph.ScenegraphDiagramGoToStep (0); SceneGraphDiagramNode.Position = new SCNVector3 (3.0f, 8.0f, 0); SceneGraphDiagramNode.Opacity = 0.0f; ContentNode.AddChildNode (SceneGraphDiagramNode); }
public SkinnedCharacter (SCNNode characterRootNode) { characterRootNode.Position = SCNVector3.Zero; AddChildNode (characterRootNode); foreach (var child in ChildNodes[0].ChildNodes) { if (child.Skinner != null) { mainSkeleton = child.Skinner.Skeleton; break; } foreach (var childOfChild in child.ChildNodes) { if (childOfChild.Skinner != null) { mainSkeleton = childOfChild.Skinner.Skeleton; break; } } } }
public static SCNNode SCAddChildNode (SCNNode container, string name, string path, nfloat scale) { // Load the scene from the specified file var scene = SCNScene.FromFile (path); // Retrieve the root node var node = scene.RootNode; // Search for the node named "name" if (name.Length > 0) node = node.FindChildNode (name, true); else node = node.ChildNodes [0]; // Take the first child if no name is passed if (scale != 0) { // Rescale based on the current bounding box and the desired scale // Align the node to 0 on the Y axis var min = new SCNVector3 (); var max = new SCNVector3 (); node.GetBoundingBox (ref min, ref max); var mid = SCNVector3.Add (min, max); mid = SCNVector3.Multiply (mid, 0.5f); mid.Y = min.Y; // Align on bottom var size = SCNVector3.Subtract (max, min); var maxSize = NMath.Max (NMath.Max (size.X, size.Y), size.Z); scale = scale / maxSize; mid = SCNVector3.Multiply (mid, scale); mid = -mid; node.Scale = new SCNVector3 (scale, scale, scale); node.Position = new SCNVector3 (mid); } // Add to the container passed in argument container.AddChildNode (node); return node; }
public override void SetupSlide (PresentationViewController presentationViewController) { TextManager.SetTitle ("Extending Scene Kit with OpenGL"); TextManager.SetSubtitle ("Material custom program"); TextManager.AddBulletAtLevel ("Custom GLSL code per material", 0); TextManager.AddBulletAtLevel ("Overrides Scene Kit’s rendering", 0); TextManager.AddBulletAtLevel ("Geometry attributes are provided", 0); TextManager.AddBulletAtLevel ("Transform uniforms are also provided", 0); // Add a torus and animate it TorusNode = Utils.SCAddChildNode (GroundNode, "torus", "Scenes/torus/torus", 10); TorusNode.Position = new SCNVector3 (8, 8, 4); TorusNode.Name = "object"; var rotationAnimation = CABasicAnimation.FromKeyPath ("rotation"); rotationAnimation.Duration = 10.0f; rotationAnimation.RepeatCount = float.MaxValue; rotationAnimation.To = NSValue.FromVector (new SCNVector4 (0, 1, 0, (float)(Math.PI * 2))); TorusNode.AddAnimation (rotationAnimation, new NSString ("torusRotation")); }
public override void SetupSlide (PresentationViewController presentationViewController) { // Load the character and add it to the scene var heroNode = Utils.SCAddChildNode (GroundNode, "bossGroup", "Scenes.scnassets/boss/boss", 0.0f); heroNode.Scale = new SCNVector3 (0.015f, 0.015f, 0.015f); heroNode.Position = new SCNVector3 (3.0f, 0.0f, 15.0f); heroNode.Rotation = new SCNVector4 (1.0f, 0.0f, 0.0f, -(float)(Math.PI / 2)); GroundNode.AddChildNode (heroNode); // Convert sceneTime-based animations into systemTime-based animations. // Animations loaded from DAE files will play according to the `currentTime` property of the scene renderer if this one is playing // (see the SCNSceneRenderer protocol). Here we don't play a specific DAE so we want the animations to animate as soon as we add // them to the scene (i.e have them to play according the time of the system when the animation was added). HeroSkeletonNode = heroNode.FindChildNode ("skeleton", true); // Load other animations so that we will use them later SetAnimation (CharacterAnimation.Attack, "attackID", "boss_attack"); }
public override void SetupSlide (PresentationViewController presentationViewController) { // Using a scene source allows us to retrieve the animations using their identifier var path = NSBundle.MainBundle.PathForResource ("Scenes.scnassets/skinning/skinning", "dae"); var sceneURL = NSUrl.FromFilename (path); var sceneSource = SCNSceneSource.FromUrl (sceneURL, (NSDictionary)null); // Place the character in the scene var error = new NSError (); var scene = sceneSource.SceneWithOption ((SCNSceneLoadingOptions)null, out error); CharacterNode = scene.RootNode.FindChildNode ("avatar_attach", true); CharacterNode.Scale = new SCNVector3 (0.004f, 0.004f, 0.004f); CharacterNode.Position = new SCNVector3 (5, 0, 12); CharacterNode.Rotation = new SCNVector4 (0, 1, 0, -(float)(Math.PI / 8)); CharacterNode.Hidden = true; GroundNode.AddChildNode (CharacterNode); SkeletonNode = CharacterNode.FindChildNode ("skeleton", true); // Prepare the other resources //TODO LoadGhostEffect (); ExtractAnimation (sceneSource); }
public override void SetupSlide (PresentationViewController presentationViewController) { // Set the slide's title and subtitle and add some text TextManager.SetTitle ("Materials"); TextManager.SetSubtitle ("Property contents"); TextManager.AddBulletAtLevel ("Color", 0); TextManager.AddBulletAtLevel ("CGColorRef / NSColor / UIColor", 0); var node = SCNNode.Create (); node.Name = "material-cube"; node.Geometry = SCNBox.Create (W, W, W, W * 0.02f); Material = node.Geometry.FirstMaterial; Material.Diffuse.Contents = NSColor.Red; Object = node; node.Position = new SCNVector3 (8, 11, 0); ContentNode.AddChildNode (node); node.RunAction (SCNAction.RepeatActionForever (SCNAction.RotateBy (NMath.PI * 2, new SCNVector3 (0.4f, 1, 0), 4))); MaterialLayerSlideReference = this; }
void CharacterNodeHitWallWithContact (SCNNode capsule, SCNPhysicsContact contact) { if (capsule.ParentNode != Character.Node) return; if (maxPenetrationDistance > contact.PenetrationDistance) return; maxPenetrationDistance = contact.PenetrationDistance; var charPosition = Character.Node.Position; SCNVector3 n = contact.ContactNormal; SCNVector3.Multiply (ref n, (float)contact.PenetrationDistance, out n); n.Y = 0; SCNVector3.Add (ref charPosition, ref n, out replacementPosition); positionNeedsAdjustment = true; }
SCNNode CreateTorchNode () { SCNGeometry geometry = SCNBox.Create (20f, 100f, 20f, 0f); geometry.FirstMaterial.Diffuse.Contents = AppKit.NSColor.Brown; var template = new SCNNode { Geometry = geometry }; var particleEmitter = new SCNNode { Position = new SCNVector3 (0f, 50f, 0f) }; SCNParticleSystem fire = GameSimulation.LoadParticleSystemWithName ("torch", "spark"); particleEmitter.AddParticleSystem (fire); particleEmitter.Light = TorchLight; template.AddChildNode (particleEmitter); return template; }
SCNNode CreateBanana () { //Create model if (bananaCollectable == null) { bananaCollectable = GameSimulation.LoadNodeWithName ("banana", GameSimulation.PathForArtResource ("level/banana.dae")); bananaCollectable.Scale = new SCNVector3 (0.5f, 0.5f, 0.5f); SCNSphere sphereGeometry = SCNSphere.Create (40); SCNPhysicsShape physicsShape = SCNPhysicsShape.Create (sphereGeometry, new SCNPhysicsShapeOptions ()); bananaCollectable.PhysicsBody = SCNPhysicsBody.CreateBody (SCNPhysicsBodyType.Kinematic, physicsShape); // Only collide with player and ground bananaCollectable.PhysicsBody.CollisionBitMask = GameCollisionCategory.Player | GameCollisionCategory.Ground; // Declare self in the banana category bananaCollectable.PhysicsBody.CategoryBitMask = GameCollisionCategory.Banana; // Rotate and Hover forever. bananaCollectable.Rotation = new SCNVector4 (0.5f, 1f, 0.5f, -(nfloat)Math.PI / 4); SCNAction idleHoverGroupAction = SCNAction.Group (new SCNAction[] { BananaIdleAction, HoverAction }); SCNAction repeatForeverAction = SCNAction.RepeatActionForever (idleHoverGroupAction); bananaCollectable.RunAction (repeatForeverAction); } return bananaCollectable.Clone (); }
SCNNode CreateLargeBanana () { //Create model if (largeBananaCollectable == null) { var node = GameSimulation.LoadNodeWithName ("banana", GameSimulation.PathForArtResource ("level/banana.dae")); float scaleMode = 0.5f * 10 / 4; node.Scale = new SCNVector3 (scaleMode, scaleMode, scaleMode); SCNSphere sphereGeometry = SCNSphere.Create (100); SCNPhysicsShape physicsShape = SCNPhysicsShape.Create (sphereGeometry, new SCNPhysicsShapeOptions ()); node.PhysicsBody = SCNPhysicsBody.CreateBody (SCNPhysicsBodyType.Kinematic, physicsShape); // Only collide with player and ground node.PhysicsBody.CollisionBitMask = GameCollisionCategory.Player | GameCollisionCategory.Ground; // Declare self in the banana category node.PhysicsBody.CategoryBitMask = GameCollisionCategory.Coin; // Rotate forever. SCNAction rotateCoin = SCNAction.RotateBy (0f, 8f, 0f, 2f); SCNAction repeat = SCNAction.RepeatActionForever (rotateCoin); node.Rotation = new SCNVector4 (0f, 1f, 0f, (nfloat)Math.PI / 2); node.RunAction (repeat); largeBananaCollectable = node; } SCNNode nodeSparkle = largeBananaCollectable.Clone (); SCNParticleSystem newSystem = GameSimulation.LoadParticleSystemWithName ("sparkle"); nodeSparkle.AddParticleSystem (newSystem); return nodeSparkle; }
public void CollideWithCoconut (SCNNode coconut, SCNVector3 contactPoint) { // No more collisions. Let it bounce away and fade out. coconut.PhysicsBody.CollisionBitMask = 0; coconut.RunAction (SCNAction.Sequence (new SCNAction[] { SCNAction.Wait (1.0), SCNAction.FadeOut (1.0), SCNAction.RemoveFromParentNode () }), () => { Coconuts.Remove ((Coconut)coconut); }); // Decrement score int amountToDrop = Score / 10; amountToDrop = Math.Max (1, amountToDrop); amountToDrop = Math.Min (10, amountToDrop); if (amountToDrop > Score) amountToDrop = Score; Score -= amountToDrop; // Throw bananas float spacing = 40f; for (int x = 0; x < amountToDrop; x++) { SCNNode banana = CreateBanana (); RootNode.AddChildNode (banana); banana.Position = contactPoint; banana.PhysicsBody.CategoryBitMask = GameCollisionCategory.NoCollide; banana.PhysicsBody.CollisionBitMask = GameCollisionCategory.Ground; SCNVector3 endPoint = SCNVector3.Zero; endPoint.X -= (spacing * x) + spacing; SCNAction flyoff = SCNAction.MoveBy (endPoint, MathUtils.RandomPercent () * 0.750f); flyoff.TimingMode = SCNActionTimingMode.EaseInEaseOut; banana.RunAction (flyoff, () => { banana.PhysicsBody.CategoryBitMask = GameCollisionCategory.Banana; banana.PhysicsBody.CollisionBitMask = GameCollisionCategory.Ground | GameCollisionCategory.Player; }); Bananas.Add (banana); } PlayerCharacter.InHitAnimation = true; }
public void CollectLargeBanana (SCNNode largeBanana) { // When the player hits a large banana, explode it into smaller bananas. // We explode into a predefined pattern: square, diamond, letterA, letterB // ignore collisions largeBanana.PhysicsBody = null; CoinsCollected++; LargeBananas.Remove (largeBanana); largeBanana.RemoveAllParticleSystems (); largeBanana.RemoveFromParentNode (); // Add to score. Score += 100; var square = new string[] { "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1" }; var diamond = new string[] { "0", "0", "1", "0", "0", "0", "1", "1", "1", "0", "1", "1", "1", "1", "1", "0", "1", "1", "1", "0", "0", "0", "1", "0", "0" }; var letterA = new string[] { "1", "0", "0", "1", "0", "1", "0", "0", "1", "0", "1", "1", "1", "1", "0", "1", "0", "0", "1", "0", "0", "1", "1", "0", "0" }; var letterB = new string[] { "1", "1", "0", "0", "0", "1", "0", "1", "0", "0", "1", "1", "0", "0", "0", "1", "0", "1", "0", "0", "1", "1", "0", "0", "0" }; var choices = new List<string[]> { square, diamond, letterA, letterB }; float vertSpacing = 40f; float spacing = 0.0075f; string[] choice = choices [new Random ().Next (0, choices.Count)]; for (int y = 0; y < 5; y++) { for (int x = 0; x < 5; x++) { int place = Int32.Parse (choice [(y * 5) + x]); if (place != 1) continue; SCNNode banana = CreateBanana (); RootNode.AddChildNode (banana); banana.Position = largeBanana.Position; banana.PhysicsBody.CategoryBitMask = GameCollisionCategory.NoCollide; banana.PhysicsBody.CollisionBitMask = GameCollisionCategory.Ground; SCNVector3 endPoint = LocationAlongPath (TimeAlongPath + spacing * (x + 1)); endPoint.Y += (vertSpacing * (y + 1)); SCNAction flyoff = SCNAction.MoveTo (endPoint, MathUtils.RandomPercent () * 0.25f); flyoff.TimingMode = SCNActionTimingMode.EaseInEaseOut; banana.RunAction (flyoff, () => { banana.PhysicsBody.CategoryBitMask = GameCollisionCategory.Banana; banana.PhysicsBody.CollisionBitMask = GameCollisionCategory.Ground | GameCollisionCategory.Player; GameSimulation.Sim.PlaySound ("deposit.caf"); }); Bananas.Add (banana); } } }
public void CollectBanana (SCNNode banana) { // Flyoff the banana to the screen space position score label. // Don't increment score until the banana hits the score label. // ignore collisions banana.PhysicsBody = null; BananasCollected++; int variance = 60; nfloat duration = 0.25f; nfloat apexY = worldSpaceLabelScorePosition.Y * 0.8f + (new Random ().Next (0, variance) - variance / 2); worldSpaceLabelScorePosition.Z = banana.Position.Z; var apex = new SCNVector3 (banana.Position.X + 10 + (new Random ().Next (0, variance) - variance / 2), apexY, banana.Position.Z); SCNAction startFlyOff = SCNAction.MoveTo (apex, duration); startFlyOff.TimingMode = SCNActionTimingMode.EaseOut; SCNAction endFlyOff = SCNAction.CustomAction (duration, new SCNActionNodeWithElapsedTimeHandler ((node, elapsedTime) => { nfloat t = elapsedTime / duration; var v = new SCNVector3 ( apex.X + ((worldSpaceLabelScorePosition.X - apex.X) * t), apex.Y + ((worldSpaceLabelScorePosition.Y - apex.Y) * t), apex.X + ((worldSpaceLabelScorePosition.Z - apex.Z) * t)); node.Position = v; })); endFlyOff.TimingMode = SCNActionTimingMode.EaseInEaseOut; SCNAction flyoffSequence = SCNAction.Sequence (new SCNAction[] { startFlyOff, endFlyOff }); banana.RunAction (flyoffSequence, () => { Bananas.Remove (banana); banana.RemoveFromParentNode (); // Add to score. Score++; GameSimulation.Sim.PlaySound ("deposit.caf"); // Game Over if (Bananas.Count == 0) DoGameOver (); }); }
public SCNNode CreateLevel () { RootNode = new SCNNode (); // load level dae and add all root children to the scene. var options = new SCNSceneLoadingOptions { ConvertToYUp = true }; SCNScene scene = SCNScene.FromFile ("level", GameSimulation.PathForArtResource ("level/"), options); foreach (SCNNode node in scene.RootNode.ChildNodes) RootNode.AddChildNode (node); // retrieve the main camera Camera = RootNode.FindChildNode ("camera_game", true); // create our path that the player character will follow. CalculatePathPositions (); // Sun/Moon light SunLight = RootNode.FindChildNode ("FDirect001", true); SunLight.EulerAngles = new SCNVector3 (7.1f * (nfloat)Math.PI / 4, (nfloat)Math.PI / 4, 0f); SunLight.Light.ShadowSampleCount = 1; lightOffsetFromCharacter = new SCNVector3 (1500f, 2000f, 1000f); //workaround directional light deserialization issue SunLight.Light.ZNear = 100f; SunLight.Light.ZFar = 5000f; SunLight.Light.OrthographicScale = 1000f; // Torches var torchesPos = new float[] { 0f, -1f, 0.092467f, -1f, -1f, 0.5f, 0.792f, 0.95383f }; for (int i = 0; i < torchesPos.Length; i++) { if (torchesPos [i] != -1) { SCNVector3 location = LocationAlongPath (torchesPos [i]); location.Y += 50; location.Z += 150; SCNNode node = CreateTorchNode (); node.Position = location; RootNode.AddChildNode (node); } } // After load, we add nodes that are dynamic / animated / or otherwise not static. CreateLavaAnimation (); CreateSwingingTorch (); AnimateDynamicNodes (); // Create our player character SCNNode characterRoot = GameSimulation.LoadNodeWithName (string.Empty, "art.scnassets/characters/explorer/explorer_skinned.dae"); PlayerCharacter = new PlayerCharacter (characterRoot); TimeAlongPath = 0; PlayerCharacter.Position = LocationAlongPath (TimeAlongPath); PlayerCharacter.Rotation = GetPlayerDirectionFromCurrentPosition (); RootNode.AddChildNode (PlayerCharacter); // Optimize lighting and shadows // only the charadcter should cast shadows foreach (var child in RootNode.ChildNodes) child.CastsShadow = false; foreach (var child in PlayerCharacter.ChildNodes) child.CastsShadow = true; // Add some monkeys to the scene. AddMonkeyAtPosition (new SCNVector3 (0f, -30f, -400f), 0f); AddMonkeyAtPosition (new SCNVector3 (3211f, 146f, -400f), -(nfloat)Math.PI / 4f); AddMonkeyAtPosition (new SCNVector3 (5200f, 330f, 600f), 0f); // Volcano SCNNode oldVolcano = RootNode.FindChildNode ("volcano", true); string volcanoDaeName = GameSimulation.PathForArtResource ("level/volcano_effects.dae"); SCNNode newVolcano = GameSimulation.LoadNodeWithName ("dummy_master", volcanoDaeName); oldVolcano.AddChildNode (newVolcano); oldVolcano.Geometry = null; oldVolcano = newVolcano.FindChildNode ("volcano", true); oldVolcano = oldVolcano.ChildNodes [0]; // Animate our dynamic volcano node. string shaderCode = "uniform float speed;\n" + "_geometry.color = vec4(a_color.r, a_color.r, a_color.r, a_color.r);\n" + "_geometry.texcoords[0] += (vec2(0.0, 1.0) * 0.05 * u_time);\n"; string fragmentShaderCode = "#pragma transparent\n"; // Dim background SCNNode back = RootNode.FindChildNode ("dumy_rear", true); foreach (var child in back.ChildNodes) { child.CastsShadow = false; if (child.Geometry == null) continue; foreach (SCNMaterial material in child.Geometry.Materials) { material.LightingModelName = SCNLightingModel.Constant; material.Multiply.Contents = AppKit.NSColor.FromDeviceWhite (0.3f, 1f); material.Multiply.Intensity = 1; } } SCNNode backMiddle = RootNode.FindChildNode ("dummy_middle", true); foreach (var child in backMiddle.ChildNodes) { if (child.Geometry == null) continue; foreach (SCNMaterial material in child.Geometry.Materials) material.LightingModelName = SCNLightingModel.Constant; } foreach (var child in newVolcano.ChildNodes) foreach (var volc in child.ChildNodes) { if (volc != oldVolcano && volc.Geometry != null) { volc.Geometry.FirstMaterial.LightingModelName = SCNLightingModel.Constant; volc.Geometry.FirstMaterial.Multiply.Contents = AppKit.NSColor.White; volc.Geometry.ShaderModifiers = new SCNShaderModifiers { EntryPointGeometry = shaderCode, EntryPointFragment = fragmentShaderCode }; } } Coconuts = new List<Coconut> (); return RootNode; }
void CollectFlower (SCNNode node) { if (node.ParentNode == null) return; SCNNode soundEmitter = SCNNode.Create (); soundEmitter.Position = node.Position; node.ParentNode.AddChildNode (soundEmitter); soundEmitter.RunAction (SCNAction.Sequence (new [] { SCNAction.PlayAudioSource (collectFlowerSound, true), SCNAction.RemoveFromParentNode () })); node.RemoveFromParentNode (); // Check if game is complete. bool gameComplete = GameView.DidCollectAFlower (); // Edit some particles. SCNMatrix4 particlePosition = soundEmitter.WorldTransform; particlePosition.M42 += 0.1f; GameView.Scene.AddParticleSystem (collectParticles, particlePosition); if (gameComplete) ShowEndScreen (); }
void CollectPearl (SCNNode node) { if (node.ParentNode == null) return; SCNNode soundEmitter = SCNNode.Create (); soundEmitter.Position = node.Position; node.ParentNode.AddChildNode (soundEmitter); soundEmitter.RunAction (SCNAction.Sequence (new [] { SCNAction.PlayAudioSource (collectPearlSound, true), SCNAction.RemoveFromParentNode () })); node.RemoveFromParentNode (); GameView.DidCollectAPearl (); }