因为需要用到手机摇一摇的功能,所以需要监听加速度变化,并把变化传到上层(LUA)。在CCLayer添加LUA回调函数,在didAccelerate里面调用CCScriptEngineManager,调用LUA注册函数。问题出现,在win32和IOS上运作正常,在android上回调一会就会崩溃,如果不回调LUA HANDLER则
没问题,应该是android的某些问题导致lua内存错误。
解决方法:修改Cocos2dxAccelerometer.java里面的onSensorChanged函数,修改回调C++部分,
@Override
public void onSensorChanged(final SensorEvent pSensorEvent) {
if (pSensorEvent.sensor.getType() != Sensor.TYPE_ACCELEROMETER) {
return;
}
float x = pSensorEvent.values[0];
float y = pSensorEvent.values[1];
final float z = pSensorEvent.values[2];
/*
* Because the axes are not swapped when the device's screen orientation
* changes. So we should swap it here. In tablets such as Motorola Xoom,
* the default orientation is landscape, so should consider this.
*/
final int orientation = this.mContext.getResources().getConfiguration().orientation;
if ((orientation == Configuration.ORIENTATION_LANDSCAPE) && (this.mNaturalOrientation != Surface.ROTATION_0)) {
final float tmp = x;
x = -y;
y = tmp;
} else if ((orientation == Configuration.ORIENTATION_PORTRAIT) && (this.mNaturalOrientation != Surface.ROTATION_0)) {
final float tmp = x;
x = y;
y = -tmp;
}
final float tx = x;
final float ty = y;
Cocos2dxActivity activity = (Cocos2dxActivity)Cocos2dxActivity.singleAcitivy;
activity.runOnGLThread(new Runnable() {
public void run() {
Cocos2dxAccelerometer.onSensorChanged(tx, ty, z, pSensorEvent.timestamp);
}
});
/*
if(BuildConfig.DEBUG) {
Log.d(TAG, "x = " + pSensorEvent.values[0] + " y = " + pSensorEvent.values[1] + " z = " + pSensorEvent.values[2]);
}
*/
}
是andoird多线程调用引起的问题,要传到C++的主线程。
在Cocos2d-x游戏开发中,为实现手机摇一摇功能,作者通过监听加速度变化触发Lua回调。然而,此方法在Android上导致应用崩溃,而iOS和Win32平台运行正常。问题出在Android的多线程调用,解决方案是确保加速度变化的回调在C++主线程中执行,避免内存错误。通过对Cocos2dxAccelerometer.java的onSensorChanged函数进行修改,确保在正确线程中处理传感器数据,解决了Android平台上的崩溃问题。
1069

被折叠的 条评论
为什么被折叠?



