Accelerometer for Android, iOS and Windows Phone

Hello,

i try to implement the accelerometer for my 2DGame with Cocosharp. I have some problems to implement the accelerometer.

Can I use the accelerometer in my shared project and use it for all other projects, or do I have to implement accelerometer for each project (Android, iOS, Windows Phone) individually.

A tutorial would be nice.

Thx 2 all

Best Answers

Answers

  • SKallSKall USMember ✭✭✭✭
    edited August 2015

    You can use the Accelerometer from XLabs.Platform (or other plugins) and use DI (XLabs.IoC) to inject the dependency to PCL.

    At application startup from the platform specific project (e.g. AppDelegate.FinishedLaunching on iOS) :

            if (!Resolver.IsSet)
            {
                var container = new SimpleContainer();
                container.Register<IAccelerometer, Accelerometer>();
                Resolver.SetResolver(container.GetResolver());
            }
    

    Then whenever you need it, use the Resolver class to get an instance:

            var accelerometer = Resolver.Resolve<IAccelerometer>();
    

    Both packages are available from NuGet. If you want more info on IoC: http://www.codenutz.com/autofac-ninject-tinyioc-unity-with-xamarin-forms-labs-xlabs/

  • dagratodagrato DEMember

    I made it work with:

    Window.Accelerometer.Enabled = true;
    var accelListener = new CCEventListenerAccelerometer();
    accelListener.OnAccelerate = DidAccelerate;
    AddEventListener(accelListener);

    But, if i switch the Layer (GameOver- Layer) and move back to the GameLayer with the Accel, it is not working anymore.

    Does someone knows why?

  • kjpou1kjpou1 LUMember, Xamarin Team Xamurai

    Not sure where you have the events being attached but try overriding OnEnter to attach and OnExit to remove

        public override void OnEnter ()
        { 
    
                }
    
        public override void OnExit ()
                {
        }
    
  • dagratodagrato DEMember

    I added the events to:

    protected override void AddedToScene()
    {
    base.AddedToScene();

          //Touch
      var touchListener = new CCEventListenerTouchAllAtOnce();
          touchListener.OnTouchesBegan = OnTouchShotandExplode;
          AddEventListener(touchListener, this);
    
       //Accel
           Window.Accelerometer.Enabled = true;
       var accelListener = new CCEventListenerAccelerometer();
       accelListener.OnAccelerate = DidAccelerate;
       AddEventListener(accelListener);
    

    }

    How do i attach the events to the OnEnter(attach) and OnExit(remove)?

Sign In or Register to comment.