Điều khiển spite bằng cảm biến gia tốc

package KDstudio.h0aKD.SensorControlExample;

import android
.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.view.Display;

import com.e3roid.E3Activity;
import com.e3roid.E3Engine;
import com.e3roid.E3Scene;
import com.e3roid.drawable.Sprite;
import com.e3roid.drawable.texture.AssetTexture;

public class SensorcontrolexampleActivity extends E3Activity implements SensorEventListener {

private int WIDTH;
private int HEIGHT;

private AssetTexture playerTexture; 
private Sprite player;
private SensorManager sensorManager;
private int getX;
private int getY;
private int moveY;
private int moveX;


@Override
public void onLoadResources() {

playerTexture = new AssetTexture("player.png", this);
}

@Override
public E3Engine onLoadEngine() {

Display display = getWindowManager().getDefaultDisplay();
WIDTH = display.getWidth();
HEIGHT = display.getHeight(); 
E3Engine engine = new E3Engine(this, WIDTH, HEIGHT);

engine.requestFullScreen();
engine.requestLandscape();
return engine;

}
@Override
public E3Scene onLoadScene() {
E3Scene scene = new E3Scene();

int centerX = (getWidth() - playerTexture.getWidth()) / 2;
int centerY = (getHeight() - playerTexture.getHeight()) / 2; 
player = new Sprite(playerTexture, centerX, centerY);

//Đăng kí để lắng nghe sự kiện thay đổi sensor
sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
sensorManager.registerListener( this,sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),1000); //delay là 1000 mili giây 

scene.getTopLayer().add(player);

return scene;
}

public void onSensorChanged(SensorEvent event) {
float[] values = event.values;
//lấy giá trị tọa độ X và Y thông qua giá trị thay đổi sensor
getX = Math.round(values[1]);
getY = Math.round(values[0]);

//Giới hạn không cho player ra khỏi scene theo chiều x
if (player.getRealX()+getX<0)
{
moveX =0;
}
else if(player.getRealX()+getX>getWidth()- playerTexture.getWidth())
{
moveX = getWidth() - playerTexture.getWidth(); 
}
else moveX=player.getRealX()+getX;

//Giới hạn không cho player ra khỏi scene theo chiều y
if (player.getRealY()+getY<0)
{
moveY =0;
}
else if(player.getRealY()+getY>getHeight()- playerTexture.getHeight())
{
moveY = getHeight() - playerTexture.getHeight(); 
}
else moveY=player.getRealY()+getY;

//Di chuyển player
player.move(moveX,moveY);
}

public void onAccuracyChanged(Sensor arg0, int arg1) {

}

}

0 nhận xét: