cocos2d-x 3.0 重力感应


一、开始学cocos2d-x没多久,其实也就是根据官方事例写的一个小Demo,直接写代码:


二、代码段


AccelerometerTest.h

#include "cocos2d.h"

USING_NS_CC;

class AccelerometerTest:public Layer
{
public:

	static Scene* createScene();

	virtual bool init();

	void onAcceleration(Acceleration* acc, Event* event);	

	CREATE_FUNC(AccelerometerTest);

    Sprite* m_ball;
};

AccelerometerTest.cpp

#include "AccelerometerTest.h"

    #define FIX_POS(_pos, _min, _max) \
    if (_pos < _min)        \
    _pos = _min;        \
    else if (_pos > _max)   \
    _pos = _max;   

Scene* AccelerometerTest::createScene()
{
	auto scene = Scene::create();
	auto layer = AccelerometerTest::create();
	scene->addChild(layer);

	return scene;

}


bool AccelerometerTest::init()
{
	if(!Layer::init())
	{
		return false;
	}

	setAccelerometerEnabled(true);
	auto listener = EventListenerAcceleration::create(CC_CALLBACK_2(AccelerometerTest::onAcceleration, this));
    _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);

	Size visibleSize = Director::getInstance()->getVisibleSize();

	auto label = Label::createWithTTF("AccelerometerTest", "fonts/Marker Felt.ttf", 32.0f);
	label->setPosition(Vec2(visibleSize.width/2,visibleSize.height-50));
	this->addChild(label);

	m_ball=Sprite::create("ball.png");
	m_ball->setPosition(Vec2(visibleSize.width/2,visibleSize.height/2));
	this->addChild(m_ball);
	

	return true;
}


void AccelerometerTest::onAcceleration(Acceleration* acc, Event* event)
{
	if(m_ball==nullptr)
	{
		return;
	}

	Size visibleSize = Director::getInstance()->getVisibleSize();
	
	auto ballSize=m_ball->getContentSize();
	auto pos=m_ball->getPosition();

	pos.x += acc->x * 9.81f;
       pos.y += acc->y * 9.81f;


	FIX_POS(pos.x,(ballSize.width/2),(visibleSize.width-ballSize.width/2));
	FIX_POS(pos.y,(ballSize.height/2),(visibleSize.height-ballSize.height/2));

	m_ball->setPosition(pos);
}

三、遇到问题

  1、      Sprite* m_ball; // 已经在头文件中定义,又在 init() 方法中 写为 auto m_ball ,导致 m_ball==nullptr


  2、      auto label = Label::createWithTTF("AccelerometerTest", "fonts/Marker Felt.ttf", 32.0f);
           // 此处字体名称写为小写,移植到Android中报错,应保持与字体文件名称大小写一致


 一些不起眼的小问题花费很多时间,脑残了

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值