简体   繁体   中英

Accelerometer with acceleration - move image Windows Phone 8

Developing a very simple-learning game for windows phone 8 in C#, i have created an acceleration vector like this:

Vector3 acceleration = accelerometerReading.Acceleration;

i cannot do anything like:

mycontrol.Xacceleration = mycontrol.Xacceleration + acceleration.X * 200;

How can i apply that acceleration to an image, i cannot find any cordinates or acceleration property. I am trying to move an image, like in labyrinth game, how can i achieve this with the acceleration? How can i apply it?

Thanks for help!

If you want to make a game with moving objects, you should look into using XNA or a game engine like Unity because the performance of C#/XAML will not be good.
If you really want to use C#/xaml you will need to calculate the postion of your image control yourself. To set the position you can put your image inside a Canvas and set the position like this:

Canvas.SetTop(myControl,XPosition);
Canvas.SetLeft(myControl,YPosition);

You can also use StoryBoard to animate the objects but it will probably be more complex if the acceleration and direction keep changing

To take advantage of hardware acceleration you will need to set CacheMode="BitmapCache" on the moving object.

Here is some code to calculate the object position:

public class ObjectInfo
    {
        public Vector2 Position { get; set; }
        public Vector2 Speed { get; set; }
        public Vector2 Acceleration { get; set; }
    }


    private DispatcherTimer dispatcherTimer;
    private int refreshTimeMilisecond = 100;
    private ObjectInfo myObject;

    public void Init()
    {
        myObject = new ObjectInfo();
        dispatcherTimer = new DispatcherTimer();
        dispatcherTimer.Interval = TimeSpan.FromMilliseconds(refreshTimeMilisecond);
        dispatcherTimer.Tick += dispatcherTimer_Tick;
    }

void dispatcherTimer_Tick(object sender, EventArgs e)
    {
        myObject.Position = myObject.Position + myObject.Speed*refreshTimeMilisecond;
        myObject.Speed = myObject.Speed + myObject.Acceleration * refreshTimeMilisecond;

        Canvas.SetTop(myControl, myObject.Position.X);
        Canvas.SetLeft(myControl, myObject.Position.Y);
    }

In xaml:

<Canvas>
    <Image x:Name="myControl" CacheMode="BitmapCache" Source="SmyleyImagePath"/>
</Canvas>

You will need to play with the refreshTimeMilisecond parameter to find out what work the best

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM