Android.mk申请权限
<uses-permission android:name="android.permission.SENSOR_INFO" /> <uses-permission android:name="android.permission.SENSOR_ENABLE" /> <activity android:screenOrientation="landscape" ></activity> 复制代码
android:screenOrientation
标题 | |
landscape | 横向 |
portrait | 纵向 |
sensor | 根据物理传感器确定方向 |
sensorLandscape | 横向方向,但根据设备传感器,可以是正常或反向的横向方向。API 9 中的新增配置。 |
网络异常,图片无法展示
|
传感器类型
传感器 | 作用 |
TYPE_ACCELEROMETER | 加速度传感器 |
TYPE_MAGNETIC_FIELD | 磁场传感器 |
横竖屏切换
在游戏的主activity中编写一个静态方法(继承Cocos2dxActivity)
public static void changedActivityOrientation(int orientation){ //activity.getRequestedOrientation() switch(orientation) { case 1://横屏 instance.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); break; case 2://竖屏 instance.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); break; } } 复制代码
- Cocos2dxAccelerometer.java
public Cocos2dxAccelerometer(final Context context) { this.mContext = context; // 获取传感器 this.mSensorManager = (SensorManager) this.mContext.getSystemService(Context.SENSOR_SERVICE); this.mAccelerometer = this.mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); this.mCompass = this.mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); final Display display = ((WindowManager) this.mContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); this.mNaturalOrientation = display.getOrientation(); } public void enableCompass() { this.mSensorManager.registerListener(this, this.mCompass, SensorManager.SENSOR_DELAY_GAME); } @Override public void onSensorChanged(final SensorEvent sensorEvent) { // 参数重载,调到jin绑定的c++层 Cocos2dxGLSurfaceView.queueAccelerometer(x,y,z,sensorEvent.timestamp); } public static native void onSensorChanged(final float x, final float y, final float z, final long timestamp); 复制代码
- Cocos2dxHelper.java
public static void enableAccelerometer() { Cocos2dxHelper.sAccelerometerEnabled = true; Cocos2dxHelper.sCocos2dxAccelerometer.enableAccel(); } public static void enableCompass() { Cocos2dxHelper.sCompassEnabled = true; Cocos2dxHelper.sCocos2dxAccelerometer.enableCompass(); } 复制代码
- CCDevice-Android.cpp
// 启用传感器 void Device::setAccelerometerEnabled(bool isEnabled) { if (isEnabled) { JniHelper::callStaticVoidMethod(helperClassName, "enableAccelerometer"); } else { JniHelper::callStaticVoidMethod(helperClassName, "disableAccelerometer"); } } 复制代码
- Java_org_cocos2dx_lib_Cocos2dxAccelerometer.cpp
extern "C" { JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxAccelerometer_onSensorChanged(JNIEnv* env, jobject thiz, jfloat x, jfloat y, jfloat z, jlong timeStamp) { Acceleration a; a.x = -((double)x / TG3_GRAVITY_EARTH); a.y = -((double)y / TG3_GRAVITY_EARTH); a.z = -((double)z / TG3_GRAVITY_EARTH); a.timestamp = (double)timeStamp / 1e9; EventAcceleration event(a); Director::getInstance()->getEventDispatcher()->dispatchEvent(&event); } } 复制代码