Place sphere in scene

Share on Twitter Share on Facebook Share on LinkedIn

Place sphere in scene

Description

We will place a basic sphere into the scene.


Video

No video yet


Code

using ARKit;
using SceneKit;
using System;
using UIKit;

namespace XamarinArkitSample
{
    public partial class ViewController : UIViewController
    {
        private readonly ARSCNView sceneView;

        public ViewController(IntPtr handle) : base(handle)
        {
            this.sceneView = new ARSCNView
            {
                AutoenablesDefaultLighting = true,
                DebugOptions = ARSCNDebugOptions.ShowWorldOrigin
            };

            this.View.AddSubview(this.sceneView);
        }

        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            this.sceneView.Frame = this.View.Frame;
        }

        public override void ViewDidAppear(bool animated)
        {
            base.ViewDidAppear(animated);

            this.sceneView.Session.Run(new ARWorldTrackingConfiguration
            {
                AutoFocusEnabled = true,
                PlaneDetection = ARPlaneDetection.Horizontal,
                LightEstimationEnabled = true,
                WorldAlignment = ARWorldAlignment.GravityAndHeading
            }, ARSessionRunOptions.ResetTracking | ARSessionRunOptions.RemoveExistingAnchors);

            // Lesson: Add sphere to scene
            var size = 0.05f;

            var sphereNode = new SphereNode(size, UIColor.White)
            {
                Position = new SCNVector3(0, 0, 0)
            };

            this.sceneView.Scene.RootNode.AddChildNode(sphereNode);

        }

        public override void ViewDidDisappear(bool animated)
        {
            base.ViewDidDisappear(animated);

            this.sceneView.Session.Pause();
        }

        public override void DidReceiveMemoryWarning()
        {
            base.DidReceiveMemoryWarning();
        }
    }

    public class SphereNode : SCNNode
    {
        public SphereNode(float size, UIColor color)
        {
            var rootNode = new SCNNode
            {
                Geometry = CreateGeometry(size, color),
                Position = new SCNVector3(0, size / 2, 0)
            };

            AddChildNode(rootNode);
        }

        private static SCNGeometry CreateGeometry(float size, UIColor color)
        {
            var geometry = SCNSphere.Create(size);
            var material = new SCNMaterial();

            material.Diffuse.Contents = color;

            geometry.Materials = new[] { material };

            return geometry;
        }
    }
}

Next Step : Place plane in scene

After you have mastered this you should try Place plane in scene