2014-03-06 35 views
0

我正在試圖用我的加速計移動一個球。但我堅持讓球移動。用JS和科爾多瓦的加速度計移動一個物體(這種情況下是球)

我得到加速度計的值,但我如何將它們與球組合起來以便它可以移動?

等待加速度計...

<div id="heading">Waiting for heading...</div> 

<div id="ball"></div> 

<script src="cordova.js"></script> 
<script src="static/js/app.js"></script> 

#ball { 
    display: block; 
    border-radius: 50%; 
    width: 50px; 
    height: 50px; 
    background-color: rgb(0,0,0); 
    color: rgb(0,0,0); 
} 


//self-invoking anonymous function 

(函數(){ '使用嚴格';

// The watch id references the current `watchAcceleration` & 'watchHeading' 
var watchID = null; 

// Initialize app with an controller object literal 
var app = { 
    // init method, Cordova is ready to be used 
    init: function() { 
     accelerometer.begin(); 
     compas.begin(); 
    }, 
} 

var accelerometer = { 
    begin: function() { 
     // Update acceleration every 100 of a second 
     var options = { 
      frequency: 100 
     }; 

     watchID = navigator.accelerometer.watchAcceleration(this.success, debug.fail, options); 
    }, 
    // Stop watching the acceleration 
    stop: function() { 
     if (watchID) { 
      navigator.accelerometer.clearWatch(watchID); 
      watchID = null; 
     } 
    }, 
    // onSuccess: Get a snapshot of the current acceleration 
    success: function (acceleration) { 
     var element = document.getElementById('accelerometer'); 
     element.innerHTML = 'Acceleration X: ' + acceleration.x + '<br />' + 
          'Acceleration Y: ' + acceleration.y + '<br />' + 
          'Acceleration Z: ' + acceleration.z + '<br />' + 
          'Timestamp: '  + acceleration.timestamp + '<br />'; 
    } 
} 

var ball = { 
    object: function() { 
     var element = document.getElementById('ball'); 
    }, 

    update: function() { 
     game.clear(); 
     newDX = accelerometer.begin.acceleration.x(); 
     newDY = accelerometer.begin.acceleration.y(); 
     newDX *= -5; 
     newDY *= -5; 
     object.setDX(newDX); 
     object.setDY(newDY); 

     ball.update(); 
    } 
} 

var compas = { 
    begin: function() { 
     // Update acceleration every 100 of a second 
     var options = { 
      frequency: 100 
     }; 

     watchID = navigator.compass.watchHeading(this.succes, debug.errormsg, options); 
    }, 
    // Stop watching the heading 
    stop: function() { 
     if (watchID) { 
      navigator.compass.clearWatch(watchID); 
      watchID = null; 
     }  
    }, 
    // onSuccess: Get a snapshot of the current heading 
    success: function (heading) { 
     var element = document.getElementById('heading'); 
     element.innerHTML = 'Heading: ' + heading.magneticHeading; 
    } 
} 

var debug = { 
    fail: function() { 
     alert('onError!'); 
    }, 
    errormsg: function (compassError) { 
     alert('Compass error: ' + compassError.code); 
    } 

} 

document.addEventListener("deviceready", app.init, false); 

})();

回答

0

試用this教程。這很簡單。

(注意:將phonegap.js更改爲cordova.js)