Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[AIR] Accelerometerから、回転角度に変換
/**
* copyright (c) 2012 www.romatica.com
* @auther itoz
* 2012.2.17 17:31:03
*/
package
{
import flash.events.AccelerometerEvent;
import flash.sensors.Accelerometer;
import flash.events.Event;
import flash.display.Sprite;
/**
* [Air] Accelerometerから、回転角度に変換.
*
* 【サンプル動画 】
* @see http://www.youtube.com/watch?v=IkPVwSv6rjE
*
*/
public class AccelerometerConvertToRotation_Sample extends Sprite
{
private var circle : Sprite;
private var rollingX : Number = 0;
private var rollingY : Number = 0;
private const FACTOR : Number = 0.5;
public function AccelerometerConvertToRotation_Sample()
{
addEventListener(Event.ADDED_TO_STAGE, onAdded);
}
private function onAdded(event : Event) : void
{
removeEventListener(Event.ADDED_TO_STAGE, onAdded);
setCircle();
setAccelerometer();
}
/**
* 円を生成
*/
private function setCircle() : void
{
circle = addChild(new Sprite()) as Sprite;
circle.graphics.beginFill(0x00cc00);
circle.graphics.drawCircle(0, 0, 64);
circle.graphics.beginFill(0x0000cc);
circle.graphics.drawCircle(50, 0, 10);
circle.graphics.endFill();
circle.x = stage.stageWidth / 2;
circle.y = stage.stageHeight / 2;
}
/**
* Accelerometerを生成
*/
private function setAccelerometer() : Boolean
{
var accelerometer : Accelerometer;
if (Accelerometer.isSupported) {
accelerometer = new Accelerometer();
if (!accelerometer.muted) {
accelerometer.setRequestedUpdateInterval(1000 / 30);
accelerometer.addEventListener(AccelerometerEvent.UPDATE, accelerometerUpdate);
return true;
}
}
return false;
}
/**
* Accelerometer アップデート
*/
private function accelerometerUpdate(event : AccelerometerEvent) : void
{
// ----------------------------------
// Accelerometerの傾きを 角度に変換
// ----------------------------------
rollingX = (event.accelerationX * FACTOR) + (rollingX * (1 - FACTOR));
rollingY = (event.accelerationY * FACTOR) + (rollingY * (1 - FACTOR));
var rad : Number = Math.atan2(rollingY, -rollingX);
var angle : Number = rad * 180 / Math.PI;
//----------------------------------
// 円を回転
//----------------------------------
if (circle != null) circle.rotation = angle;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.