Home » Moving an object with the accelerometer

Moving an object with the accelerometer

by Online Tutorials Library

Moving an object with the accelerometer

In our previous section, we read the device accelerometer using PhoneGap. In this section, we will look at the accelerometer wreathing and use it to do something constructive, like moving an object on the screen. We will make some changes to our previous example. These are the following steps used to move an object with the accelerometer:

1) Creating index2.html

We will create a new file index2.html with the same code as preset in the index.html. We will make changes later in index2.html file not in index.html.

Moving an object with the accelerometer

2) Creating a red block for movement

Now, we will create a block for movement using <div></div> tag. We will give it an Id using id attribute because JavaScript doesn’t know the HTML tags.

3) Change style of the red block

We will change the style of the red block by using the <style></style> tag. We will set the background color, width, and height in the following way:

4) Make changes in the window.onload function

We will make changes in the success function. If the X acceleration is less than 0, we will take x position variable, which marks the X position of the red square on the X-axis and add the absolute value of the acceleration X value to that position.

Otherwise, we will make the xPos a negative number, by multiplying with the negative 1 in the following way:

Complete Code:

Output

Moving an object with the accelerometer


You may also like