我是初学者,从cocos2d-x开始。我想要克隆游戏 -
https://play.google.com/store/apps/details?id=com.addictivegames.angryalcohol&hl=en
这似乎很容易,但结果我在“更新功能”(游戏循环)中使用的逻辑不起作用。 这是我的代码 -
#include "MainGameScene.h"
#include "MainMenuScene.h"
#include "GameOverScene.h"
#include "Constants.h"
USING_NS_CC;
Scene* MainGameScene::createScene()
{
// 'scene' is an autorelease object
auto scene = Scene::create();
// 'layer' is an autorelease object
auto layer = MainGameScene::create();
auto layer2 = MainGameScene::create();
// add layer as a child to scene
scene->addChild(layer);
scene->addChild(layer2);
// return the scene
return scene;
}
// on "init" you need to initialize your instance
bool MainGameScene::init()
{
//////////////////////////////
// 1. super init first
if ( !Layer::init() )
{
return false;
}
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
// this will now place the sprite in the middle of the viewport
sprite = Sprite::create("top.png");
sprite->setPosition(Point( visibleSize.width/2 + origin.x, visibleSize.height/3 + origin.y));
sprite->setAnchorPoint( Vec2( 0.5, 0 ));
this->addChild( sprite );
//Accelerometer Setup here...
Device::setAccelerometerEnabled(true);
auto acclistener = EventListenerAcceleration::create(CC_CALLBACK_2(MainGameScene::onAcceleration, this));
Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(acclistener, this);
this->scheduleUpdate();
return true;
}
void MainGameScene::onAcceleration(cocos2d::Acceleration *acc, cocos2d::Event *event) {
//Position constraints
Size winSize = Director::getInstance()->getWinSize();
float rotX = sprite->getRotation();
float w = winSize.width ;
float h = winSize.height;
float center = winSize.width/2 ;
currentPos = sprite->getPositionX();
float y = sprite->getPositionY();
float spriteWidth = sprite->getContentSize().width;
//Filters for acceleration
float sensitivity = 0.3;
float kFilteringFactor = 0.4;
//Accelerometer To control natural movement (GAME_LOOP_CONTROL)
float accelX = ( acc->x * kFilteringFactor ) + ( accelX * (1.0 - kFilteringFactor ));
rotX = accelX - acc->x ;
currentPos += acc->x * w * sensitivity;
sprite->setPosition(currentPos, y);
//sprite->setRotationX(rotX);
}
void MainGameScene::update( float dt ){
Size winSize = Director::getInstance()->getWinSize();
float w = winSize.width ;
if (currentPos > winSize.width/2){ // IF on right side from middle
currentPos += 50 * w ;
} else if (currentPos < winSize.width/2 ){ // IF on left side from middle
currentPos -= 50 * w ;
}
sprite->setPosition(currentPos, sprite->getPositionY());
}
加速度计的玩家移动很好 我确定,游戏循环中有问题。任何形式的帮助将不胜感激。提前谢谢!
另外,我正在考虑从cocos2d-x切换到unity。这个决定是否有希望?
答案 0 :(得分:1)
问题是你突然在每个帧中更新精灵的位置,因此精灵在任何位置都不可见。你必须让精灵停留在某个时间点或平稳地更新它的位置(比如使用MoveTo)。这是一个例子。你不应该要求解决方案而不是如何解决问题。
step