Android how to detect if phone is turned around - android

This is my code for detecting if phone is turned around or not
private SensorManager sensorManager;
private int orientationLim = 165;
#Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ORIENTATION) {
// If shake to stop is enabled
boolean turnAroundToStop = Utils.getBooleanFromProperties(this, Properties.SP_CB_TURN_AROUND_TO_STOP);
if (turnAroundToStop) {
float value = Math.abs(event.values[1]);
if (value > orientationLim && !stopped) {
// Down
stopped = true;
} else {
// Up
stopped = false;
}
}
}
}
but problem is that stopped variable is set to true even phone is not completely turned around but just a little.
How can i modify this code that will be executed only when phone is relay turned around.

float pitch = values[2];
if (pitch <= 45 && pitch >= -45) {
// mostly vertical
} else if (pitch < -45) {
// mostly right side up
} else if (pitch > 45) {
// mostly left side up
}
Take a look here on this topic:
http://www.workingfromhere.com/blog/2009/03/30/orientation-sensor-tips-in-android/

Related

Low Pass Filter android

I am trying to adapt a low pass filter from this site:
Low Pass Filter
My problem is that I do not know what is the goal of below line:
int rotation = Compatibility.getRotation(this);
I have googled a lot in order to search information about this but without no luck. Anyone knows what it does?
See below piece of code:
#Override
public void onSensorChanged(SensorEvent evt) {
if (evt.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
gravSensorVals = lowPass(evt.values.clone(), gravSensorVals);
} else if (evt.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
magSensorVals = lowPass(evt.values.clone(), magSensorVals);
}
if (gravSensorVals != null && magSensorVals != null) {
SensorManager.getRotationMatrix(RTmp, I, gravSensorVals, magSensorVals);
int rotation = Compatibility.getRotation(this);
if (rotation == 1) {
SensorManager.remapCoordinateSystem(RTmp, SensorManager.AXIS_X, SensorManager.AXIS_MINUS_Z, Rot);
} else {
SensorManager.remapCoordinateSystem(RTmp, SensorManager.AXIS_Y, SensorManager.AXIS_MINUS_Z, Rot);
}
SensorManager.getOrientation(Rot, results);
UIARView.azimuth = (float)(((results[0]*180)/Math.PI)+180);
UIARView.pitch = (float)(((results[1]*180/Math.PI))+90);
UIARView.roll = (float)(((results[2]*180/Math.PI)));
radarMarkerView.postInvalidate();
}
}
From android documentation: here, it will check the device orientation. So value of one is ROTATION_90. device rotated 90 degrees counter clockwise.

Android: A Slight Change in Accelerometer Sensor calls an activity many times.

I'm developing a simple android game. I'm new to android and now I got stuck into this logical error.
The game only uses accelerometerSensor and Text to Speech. A voice tells you to perform some action (e.g. tilting the device up, down, left, right etc.) And if you do it, your score will be incremented (Now I'm done with all this part.) and if not, you are asked to try again.
But the problem is of making the game challenging. To make it challenging, I want that if the user tilts the device in wrong direction he looses it and the game starts again with the score of 0.
As I'm using accelerometer sensor. So a slight change in the sensor calls onSensorChanged many times.
Think of it like this, the user is playing the game, and is asked to perform some action e.g. "Up". As he is moving the device upwards, in the mean time onSensorChanged is called many times and is reporting the if condition as wrong so it goes to the else block, which say Start another activity (the try again page). Instead of starting the activity only once, it starts it too many times until the condition is correct.
What I want is that if the user does it wrong, he is asked to try again in another activity only once. Not hundred times.
The onSensorChanged and onAccelerometerChanged looks like this:
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
onAccelerometerChanged(event);
}
}
private void onAccelerometerChanged(SensorEvent event) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setClass(this, Loose.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
int x = (int) event.values[0];
int y = (int) event.values[1];
int z = (int) event.values[2];
mAccelLast = mAccelCurrent;
mAccelCurrent = (float) Math.sqrt((double) (x * x + y * y + z * z));
float delta = mAccelCurrent - mAccelLast;
mAccel = mAccel * 0.9f + delta; // perform low-cut filter
if (write.getText() == arr[0]) {
// Waiter.run();
if (y == 9) { // for Y aka Up
Log.d(TAG, "onAccelerometerChanged for Y Called!");
powerUp.start();
// Toast.makeText(getApplicationContext(), "Up! Very Good!",
// Toast.LENGTH_SHORT).show();
status.setText("Up! Very Good!");
scoreInt += 1;
score.setText(String.valueOf(scoreInt));
BeginPlaying();
}
else {
// powerDown.start();
// scoreInt -= 1;
// mSensorManager.unregisterListener(this);
// score.setText(String.valueOf(scoreInt));
startActivity(intent);
}
}
else if (write.getText() == arr[1]) {
// Waiter.run();
if (y == -9) { // for -Y aka Down
powerUp.start();
Log.d(TAG, "onAccelerometerChanged for -Y Called!");
scoreInt += 1;
score.setText(String.valueOf(scoreInt));
status.setText("Down! Very Good!");
BeginPlaying();
}
else {
// powerDown.start();
// scoreInt -= 1;
// score.setText(String.valueOf(scoreInt));
// mSensorManager.unregisterListener(this);
startActivity(intent);
}
}
else if (write.getText() == arr[2]) {
// Waiter.run();
if (x == -9) { // for -X aka Left
powerUp.start();
Log.d(TAG, "onAccelerometerChanged for -X Called!");
scoreInt += 1;
score.setText(String.valueOf(scoreInt));
status.setText("NegSide! Very Good!");
BeginPlaying();
} else {
// powerDown.start();
// scoreInt -= 1;
// score.setText(String.valueOf(scoreInt));
// mSensorManager.unregisterListener(this);
startActivity(intent);
}
}
else if (write.getText() == arr[3]) {
// Waiter.run();
if (x == 9) { // for X aka Right
powerUp.start();
Log.d(TAG, "onAccelerometerChanged for X Called!");
scoreInt += 1;
score.setText(String.valueOf(scoreInt));
status.setText("Side! Very Good!");
BeginPlaying();
}
else {
// powerDown.start();
// scoreInt -= 1;
// score.setText(String.valueOf(scoreInt));
// mSensorManager.unregisterListener(this);
startActivity(intent);
}
}
else if (write.getText() == arr[4]) {
// Waiter.run();
if (z == -9) { // for Back
powerUp.start();
Log.d(TAG, "onAccelerometerChanged for Upside Down Called!");
scoreInt += 1;
score.setText(String.valueOf(scoreInt));
status.setText("Upside Down! Very Good!");
BeginPlaying();
}
else {
// powerDown.start();
// scoreInt -= 1;
// score.setText(String.valueOf(scoreInt));
// mSensorManager.unregisterListener(this);
startActivity(intent);
}
}
else if (write.getText() == arr[5]) {
// Waiter.run();
if (z == 9) { // for Front aka Right Side Up
powerUp.start();
Log.d(TAG, "onAccelerometerChanged for Z Called!");
scoreInt += 1;
score.setText(String.valueOf(scoreInt));
status.setText("Front! Very Good!");
BeginPlaying();
}
else {
// powerDown.start();
// scoreInt -= 1;
// score.setText(String.valueOf(scoreInt));
// mSensorManager.unregisterListener(this);
startActivity(intent);
}
}
else if (write.getText() == arr[6]) { // tap
// Waiter.run();
layout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (write.getText() == arr[6]) {
powerUp.start();
scoreInt += 1;
score.setText(String.valueOf(scoreInt));
status.setText("Tap! Very Good!");
BeginPlaying();
}
}
});
}
else if (write.getText() == arr[7]) {
// Waiter.run();
if (mAccel > 2) { // for Shake
powerUp.start();
Log.d(TAG, "onAccelerometerChanged for Shake Called!");
status.setText("Shake! Very Good!");
scoreInt += 1;
score.setText(String.valueOf(scoreInt));
BeginPlaying();
}
else {
// powerDown.start();
// scoreInt -= 1;
// score.setText(String.valueOf(scoreInt));
// mSensorManager.unregisterListener(this);
startActivity(intent);
}
}
}
The calling function BeginPlaying() is:
private void BeginPlaying() {
// TODO Auto-generated method stub
if (scoreInt > 10) {
ttobj.setSpeechRate(2);
}
if (scoreInt > 18) {
ttobj.setSpeechRate(3);
}
if (scoreInt > 30) {
SharedPreferences scoreValues = getSharedPreferences(
"MyScoreValues", 0);
SharedPreferences.Editor editor = scoreValues.edit();
editor.putString("SValue", score.getText().toString());
editor.commit();
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
// powerUp.start();
randSelect = randGen.nextInt(arr.length);
write.startAnimation(animPushin);
write.setText(arr[randSelect]);
speakTextSensor();
// SystemClock.sleep(2000);
}
The arr[] is the array that contains the actions to be spoken and displayed on screen.
The speakTextSensor() is:
public void speakTextSensor() {
String toSpeak = write.getText().toString();
// Toast.makeText(getApplicationContext(), toSpeak, Toast.LENGTH_SHORT)
// .show();
ttobj.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
}
I've used unRegisterListener, SystemClock.sleep(), Handlers.. But they don't seem to solve the issue.
It would be really kind and helpful if someone solves the issue.
You don't seem to understand how an accelerometer works. Imageine there was a pliable metal spring made of thin foil on the outside of your phone. When you move it away, the base of the spring moves first so the spring expands a little. When you move it twoards you, it contracts. When it goes back to normal (from either direction) it bounces a bit, with each bounce (usually) shorter than the previous one until its imperceptable. That's basically an accelerometer. Notice that means if you move it forwards then stop that this will happen twice (once for start and once for stopping) and the two waveforms can have positive and negative interference.
(This isn't quite how a modern accelereometer works and its incomplete, but its a simplification to explain it)
The accelerometer sensor gives you the raw data of what the accelerometer currently reads. It doesn't account for the bouncing, or for the time it takes to go back to normal, or anything like that. You have to. The processing of that data is called DSP (digital signal processing) and learning how to do it can take years.
In your particular case, there might be an easy out. Simply make it so that when you detect an event strong enough for you to trigger, debounce. Save the time that it occurs at, and don't process any more events for 1 second (or whatever length of time you feel appropriate). That will fix your current problem.
Here's two other major issues with your code as freebies:
1)Your z code will either go off way too often or all the time. Thats because z is almost always 9 or 10, due to gravity. Unless the phone is held at an angle of course, in which case it will be lower and some of the others will be higher than 0 when held still.
2)If you were using the value 9 because it seemed to work well when the device was put completely on its side (due to gravity), don't. Some devices will actually read 10 due to gravity, these devices aren't well callibrated (mine reads 10.23 by default).

how to calculate exact foot step count using accelerometer in android?

I am developing some application like Runtastic Pedometer using the algorithm but I am not getting any similarity between the results.
my code is as follows:
public void onSensorChanged(SensorEvent event)
{
Sensor sensor = event.sensor;
synchronized (this)
{
if (sensor.getType() == Sensor.TYPE_ORIENTATION) {}
else {
int j = (sensor.getType() == Sensor.TYPE_ACCELEROMETER) ? 1 : 0;
if (j == 1) {
float vSum = 0;
for (int i=0 ; i<3 ; i++) {
final float v = mYOffset + event.values[i] * mScale[j];
vSum += v;
}
int k = 0;
float v = vSum / 3;
//Log.e("data", "data"+v);
float direction = (v > mLastValues[k] ? 1 : (v < mLastValues[k] ? -1 : 0));
if (direction == - mLastDirections[k]) {
// Direction changed
int extType = (direction > 0 ? 0 : 1); // minumum or maximum?
mLastExtremes[extType][k] = mLastValues[k];
float diff = Math.abs(mLastExtremes[extType][k] - mLastExtremes[1 - extType][k]);
if (diff > mLimit) {
boolean isAlmostAsLargeAsPrevious = diff > (mLastDiff[k]*2/3);
boolean isPreviousLargeEnough = mLastDiff[k] > (diff/3);
boolean isNotContra = (mLastMatch != 1 - extType);
if (isAlmostAsLargeAsPrevious && isPreviousLargeEnough && isNotContra) {
for (StepListener stepListener : mStepListeners) {
stepListener.onStep();
}
mLastMatch = extType;
}
else {
Log.i(TAG, "no step");
mLastMatch = -1;
}
}
mLastDiff[k] = diff;
}
mLastDirections[k] = direction;
mLastValues[k] = v;
}
}
}
}
for registering sensors:
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mSensor = mSensorManager.getDefaultSensor(
Sensor.TYPE_ACCELEROMETER);
mSensorManager.registerListener(mStepDetector,mSensor,SensorManager.SENSOR_DELAY_NORMAL);
in the algorithm i have different levels for sensitivity as public void
setSensitivity(float sensitivity) {
mLimit = sensitivity; // 1.97 2.96 4.44 6.66 10.00 15.00 22.50 33.75 50.62
}
on various sensitivity level my result is:
sensitivity rantastic pedometer my app
10.00 3870 5500
11.00 3000 4000
11.15 3765 4576
13.00 2000 890
11.30 754 986
I am not getting any proper pattern to match with the requirement.
As per my analysis this application is using Sensor.TYPE_MAGNETIC_FIELD for steps calculation please let me know some algorithm so that I can meet with the requirement.
The first thing you need to do is decide on an algorithm. As far as I know there are roughly speaking three ways to detect steps using accelerometers that are described in the literature:
Use the Pythagorean theorem to calculate the magnitude of the acceleration vector of each sample from the accelerometer. Low-pass filter the magnitude signal to remove high frequency noise and then look for peaks and valleys in the filtered signal. You may need to add additional requirements to remove false positives. This is by far the simplest way to detect steps, it is also the way that most if not all ordinary pedometers of the sort that you can buy from a sports store work.
Use Pythagoras' like in (1), then run the signal through an FFT and compare the output from the FFT to known outputs of walking. This requires you to have access to a fairly large amount of training data.
Feed the accelerometer data into an algorithm that uses some suitable machine learning technique, for example a neural network or a digital wavelet transform. You can of course include other sensors in this approach. This also requires you to have access to a fairly large amount of training data.
Once you have decided on an algorithm you will probably want to use something like Matlab or SciPy to test your algorithm on your computer using recordings that you have made on Android phones. Dump accelerometer data to a cvs file on your phone, make a record of how many steps the file represents, copy the file to your computer and run your algorithm on the data to see if it gets the step count right. That way you can detect problems with the algorithm and correct them.
If this sounds difficult, then the best way to get access to good step detection is probably to wait until more phones come with the built-in step counter that KitKat enables.
https://github.com/bagilevi/android-pedometer
i hope this might be helpfull
I am using step detection in my walking instrument.
I get nice results of step detection.
I use achartengine to plot accelerometer data.
Take a look here.
What I do:
Analysis of magnitude vector for accelerometer sensor.
Setting a changeable threshold level. When signal from accelerometer is above it I count it as a step.
Setting the time of inactive state (for step detection) after first crossing of the threshold.
Point 3. is calculated:
arbitrary setting the maximum tempo of our walking (e.g. 120bpm)
if 60bpm - 1000msec per step, then 120bpm - 500msec per step
accelerometer passes data with certain desired frequency (SENSOR_DELAY_NORMAL, SENSOR_DELAY_GAME, etc.). When DELAY_GAME: T ~= 20ms (this is included in Android documentation)
n - samples to omit (after passing the threshold)
n = 500msec / T
n = 500 / 20 = 25 (plenty of them. You can adjust this value).
after that, the threshold becomes active.
Take a look at this picture:
This is my realization. It was written about 1.5-2 years ago. And I really don't remember all this stuff that I wrote. But it worked. And it worked good for my needs.
I know that this is really big class (some methods are deleted), but may be it will be helpful. If not, I'll just remove this answer...
public class StepDetector implements SensorEventListener
{
public static final int MAX_BUFFER_SIZE = 5;
private static final int Y_DATA_COUNT = 4;
private static final double MIN_GRAVITY = 2;
private static final double MAX_GRAVITY = 1200;
public void onSensorChanged(final SensorEvent sensorEvent)
{
final float[] values = sensorEvent.values;
final Sensor sensor = sensorEvent.sensor;
if (sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
{
magneticDetector(values, sensorEvent.timestamp / (500 * 10 ^ 6l));
}
if (sensor.getType() == Sensor.TYPE_ACCELEROMETER)
{
accelDetector(values, sensorEvent.timestamp / (500 * 10 ^ 6l));
}
}
private ArrayList<float[]> mAccelDataBuffer = new ArrayList<float[]>();
private ArrayList<Long> mMagneticFireData = new ArrayList<Long>();
private Long mLastStepTime = null;
private ArrayList<Pair> mAccelFireData = new ArrayList<Pair>();
private void accelDetector(float[] detectedValues, long timeStamp)
{
float[] currentValues = new float[3];
for (int i = 0; i < currentValues.length; ++i)
{
currentValues[i] = detectedValues[i];
}
mAccelDataBuffer.add(currentValues);
if (mAccelDataBuffer.size() > StepDetector.MAX_BUFFER_SIZE)
{
double avgGravity = 0;
for (float[] values : mAccelDataBuffer)
{
avgGravity += Math.abs(Math.sqrt(
values[0] * values[0] + values[1] * values[1] + values[2] * values[2]) - SensorManager.STANDARD_GRAVITY);
}
avgGravity /= mAccelDataBuffer.size();
if (avgGravity >= MIN_GRAVITY && avgGravity < MAX_GRAVITY)
{
mAccelFireData.add(new Pair(timeStamp, true));
}
else
{
mAccelFireData.add(new Pair(timeStamp, false));
}
if (mAccelFireData.size() >= Y_DATA_COUNT)
{
checkData(mAccelFireData, timeStamp);
mAccelFireData.remove(0);
}
mAccelDataBuffer.clear();
}
}
private void checkData(ArrayList<Pair> accelFireData, long timeStamp)
{
boolean stepAlreadyDetected = false;
Iterator<Pair> iterator = accelFireData.iterator();
while (iterator.hasNext() && !stepAlreadyDetected)
{
stepAlreadyDetected = iterator.next().first.equals(mLastStepTime);
}
if (!stepAlreadyDetected)
{
int firstPosition = Collections.binarySearch(mMagneticFireData, accelFireData.get(0).first);
int secondPosition = Collections
.binarySearch(mMagneticFireData, accelFireData.get(accelFireData.size() - 1).first - 1);
if (firstPosition > 0 || secondPosition > 0 || firstPosition != secondPosition)
{
if (firstPosition < 0)
{
firstPosition = -firstPosition - 1;
}
if (firstPosition < mMagneticFireData.size() && firstPosition > 0)
{
mMagneticFireData = new ArrayList<Long>(
mMagneticFireData.subList(firstPosition - 1, mMagneticFireData.size()));
}
iterator = accelFireData.iterator();
while (iterator.hasNext())
{
if (iterator.next().second)
{
mLastStepTime = timeStamp;
accelFireData.remove(accelFireData.size() - 1);
accelFireData.add(new Pair(timeStamp, false));
onStep();
break;
}
}
}
}
}
private float mLastDirections;
private float mLastValues;
private float mLastExtremes[] = new float[2];
private Integer mLastType;
private ArrayList<Float> mMagneticDataBuffer = new ArrayList<Float>();
private void magneticDetector(float[] values, long timeStamp)
{
mMagneticDataBuffer.add(values[2]);
if (mMagneticDataBuffer.size() > StepDetector.MAX_BUFFER_SIZE)
{
float avg = 0;
for (int i = 0; i < mMagneticDataBuffer.size(); ++i)
{
avg += mMagneticDataBuffer.get(i);
}
avg /= mMagneticDataBuffer.size();
float direction = (avg > mLastValues ? 1 : (avg < mLastValues ? -1 : 0));
if (direction == -mLastDirections)
{
// Direction changed
int extType = (direction > 0 ? 0 : 1); // minumum or maximum?
mLastExtremes[extType] = mLastValues;
float diff = Math.abs(mLastExtremes[extType] - mLastExtremes[1 - extType]);
if (diff > 8 && (null == mLastType || mLastType != extType))
{
mLastType = extType;
mMagneticFireData.add(timeStamp);
}
}
mLastDirections = direction;
mLastValues = avg;
mMagneticDataBuffer.clear();
}
}
public static class Pair implements Serializable
{
Long first;
boolean second;
public Pair(long first, boolean second)
{
this.first = first;
this.second = second;
}
#Override
public boolean equals(Object o)
{
if (o instanceof Pair)
{
return first.equals(((Pair) o).first);
}
return false;
}
}
}
One main difference I spotted between your implementation and the code in the grepcode project is the way you register the listener.
Your code:
mSensorManager.registerListener(mStepDetector,
mSensor,
SensorManager.SENSOR_DELAY_NORMAL);
Their code:
mSensorManager.registerListener(mStepDetector,
mSensor,
SensorManager.SENSOR_DELAY_FASTEST);
This is a big difference. SENSOR_DELAY_NORMAL is intended for orientation changes, and is therefor not that fast (ever noticed that it takes some time between you rotating the device, and the device actually rotating? That's because this is some functionality that does not need to be super fast (that would probably be pretty annoying even). The rate at which you get updates is not that high).
On the other hand, SENSOR_DELAY_FASTEST is intended for things like pedometers: you want the sensor data as fast and often as possible, so your calculations of steps will be as accurate as possible.
Try to switch to the SENSOR_DELAY_FASTEST rate, and test again! It should make a big difference.
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType()==Sensor.TYPE_ACCELEROMETER ){
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
currentvectorSum = (x*x + y*y + z*z);
if(currentvectorSum < 100 && inStep==false){
inStep = true;
}
if(currentvectorSum > 125 && inStep==true){
inStep = false;
numSteps++;
Log.d("TAG_ACCELEROMETER", "\t" + numSteps);
}
}
}

Move animated movieClips using buttons instead of arrow keys

I'm trying to develop a game where I want my character to run when I click a button, and continue running if I hold the button. I'm new to ActionScript 3, so I'm a bit lost here.
I've found code that satisfies my requirements; but it uses the arrow keys, as below:
function moveRunKei() {
if (Key.isDown(Key.RIGHT)) {
dx = 15; //speed
runKei._xscale = 50;
} else if (Key.isDown(Key.LEFT)) {
dx = -15;
runKei._xscale = -50;
} else {
dx = 0;
}
runKei._x += dx;
if (runKei._x < 100) runKei._x = 100; //30
if (runKei._x > 550) runKei._x = 550;
if (dx != 0 && runKei._currentframe == 1) {
runKei.gotoAndPlay("run");
} else if (dx == 0 && runKei._currentframe != 1) {
runKei.gotoAndStop("stand");
}
}
this.onEnterFrame = function(){
moveRunKei();
}
I need to be able to do this using buttons.
////////////////////////////////////////////////////////////////////////////////////
import flash.events.Event;
var mouseDown:Boolean;
var speed:Number=4;
addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
addEventListener(Event.ENTER_FRAME, onEnterFrame);
function onMouseDown(event:MouseEvent):void
{
mouseDown = true;
}
function onMouseUp(event:MouseEvent):void
{
mouseDown = false;
}
function onEnterFrame(event:Event):void
{
if (mouseDown)
{
runKei.gotoAndPlay("Run");
runKei.x += speed;
}
}
This code able to make my character move continuously when I hold the button but it didn't animate while it move(the character freeze until I release the button) - I'm not sure how to explain it.
You'll need to add event listeners for mouse down and mouse up on each of the buttons for movement. Then have booleans that keep track of whether or not the button is down.
It's worth mentioning the code you've linked seems to be actionscript2 so I've changed it to work with as3
var leftDown:Boolean = false;
var rightDown:Boolean = true;
leftButton.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown)
rightButton.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown)
leftButton.addEventListener(MouseEvent.MOUSE_UP, onMouseUp)
rightButton.addEventListener(MouseEvent.MOUSE_UP, onMouseUp)
leftButton.addEventListener(MouseEvent.MOUSE_OUT, onMouseUp)
rightButton.addEventListener(MouseEvent.MOUSE_OUT, onMouseUp)
function onMouseDown(e:MouseEvent):void
{
//since you can't click on two things at once, this is fine.
rightDown = (e.target == rightButton);
leftDown = (e.target == rightButton);
}
function onMouseDown(e:MouseEvent):void
{
//since you can't click on two things at once, this is fine.
rightDown = (e.target == rightButton);
leftDown = (e.target == leftButton);
}
function moveRunKei()
{
if (rightDown) {
dx = 15; //speed
runKei.scaleX = -0.5;
} else if (leftDown) {
dx = -15;
runKei.scaleX = -0.5;
} else {
dx = 0;
}
runKei.x += dx;
if (runKei.x < 100) runKei.x = 100; //30
if (runKei.x > 550) runKei.x = 550;
if (dx != 0 && runKei.currentFrame == 1)
{
runKei.gotoAndPlay("run");
}
else if (dx == 0 && runKei.currentFrame != 1)
{
runKei.gotoAndStop("stand");
}
}
this.addEventListener(Event.ENTER_FRAME, onEnterFrame);
function onEnterFrame(e:Event):void
{
moveRunKei();
}

Android sensors to control game

I'm trying to setup my android game to use android sensors for controlling the game.
When the phone is tilted forwards slightly, I want the thrusters to fire.
And tilting the phone left or right rotates it in the rescpetive direction.
At the moment, I'm using TYPE_ORIENTATION as follows:
public void onSensorChanged(SensorEvent event) {
if(mMode == STATE_RUNNING) {
synchronized (mSurfaceHolder) {
//rotation
float pitch = event.values[2]; // pitch
if(pitch <= 15 & pitch >= -15) {
mRotating = 0;
} else if(pitch < -15) {
mRotating += 1;
} else if(pitch > 15) {
mRotating -= 1;
}
//thrust by tilting forward!
if(event.values[0] > 0) {
thrusterFiring = true;
} else {
thrusterFiring = false;
}
}
}
}
But I'm not sure if this is quite right? Additionally, you have to filt the phone quite a bit forwards in order for the thrusters to fire - I'd like it so you only need to tilt a little!
Any help appreciated!

Categories

Resources