Cocos 2dx重力感应系统
//调用安卓重力加速器
//重写onAcceleration方法
virtual void onAcceleration(Acceleration* acc, Event* unused_event);
//创建控制对象
Sprite* img=Sprite::create(“图片路径”);
img->setPosition(cocos2d::Vec2(640.0f, 360.0f));
addChild(img, 100);
//开启重力检测
this->setAccelerometerEnabled(true);
//实现onAcceleration方法
#define SPEED 20
//重写重力加速器方法
void VMainScene::onAcceleration(Acceleration* acc, Event* event){
auto director = Director::getInstance();
if (img == NULL){
return;
}
//获得sprite坐标
Vec2 vec = img->getPosition();
//获得当前x、y轴坐标
float x = vec.x;
float y = vec.y;
//获得移动距离
double disX = acc->x * SPEED;
double disY = acc->y * SPEED;
img->setPosition(Vec2(x + disX, y + disY));
log("onAcceleration: acc->x: %f, acc->y: %f, acc->z: %f, imgX: %f, imgY: %f",acc->x, acc->y, acc->z, disX, disY);
}
注:只有在安卓上才有效果,电脑上甚至都不会调此方法