我刚开始学习 coco2dx for android,我已经成功配置了我的环境,但我面临的问题很少。
- 当我在我的设备上触摸时,我正在添加一个 sprite。检测到触摸事件,但我无法在我的屏幕上添加 Sprite 。
- 我无法在 cocos2dx 的 eclipse 中获得自动完成功能。
- 我的头文件出现语法错误(HelloWorld.h 中的“cocos2d.h”和 HelloWorld.cpp 中的“USING_NS_CC”)。但我在编译时没有遇到任何错误。
下面是我的代码:
Hello World .h
#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__
#include "cocos2d.h"
class HelloWorld : public cocos2d::CCLayer
{
public:
virtual bool init();
static cocos2d::CCScene* scene();
void menuCloseCallback(CCObject* pSender);
void ccTouchesBegan(cocos2d::CCSet* pTouches, cocos2d::CCEvent* pEvent);
LAYER_CREATE_FUNC(HelloWorld);
};
#endif // __HELLOWORLD_SCENE_H__
Hello World .cpp
#include "HelloWorldScene.h"
USING_NS_CC;
CCScene* HelloWorld::scene()
{
CCScene *scene = CCScene::create();
HelloWorld *layer = HelloWorld::create();
scene->addChild(layer);
return scene;
}
bool HelloWorld::init()
{
if ( !CCLayer::init() )
{
return false;
}
CCSize size = CCDirector::sharedDirector()->getWinSize();
CCSprite* bg = CCSprite::create("moles_bg.png");
bg->setPosition( ccp(size.width/2, size.height/2) );
this->addChild(bg, -1);
float rX = size.width / bg->getContentSize().width;
float rY = size.height / bg->getContentSize().height;
bg->setScaleX(rX);
bg->setScaleY(rY);
this->setTouchEnabled(true);
return true;
}
void HelloWorld::ccTouchesBegan(cocos2d::CCSet* pTouches, cocos2d::CCEvent* pEvent)
{
CCTouch* touch = (CCTouch* )pTouches->anyObject();
CCPoint location = touch->locationInView();
location = CCDirector::sharedDirector()->convertToGL(location);
CCSprite* sprite = CCSprite::create("moles_icon.png");
sprite->setPosition(location);
sprite->addChild(sprite, 1);
//This is shown in my log cat
CCLog("Sprite Touched");
}
我的环境配置如下:
- 操作系统:Win7
- Cocos2d-x 版本:cocos2dx 2.0.1
- eclipse :来自 here (不知道是哪个版本)。
对于上述问题的任何帮助将不胜感激:)
最佳答案
改变
sprite->addChild(sprite, 1);
到
this->addChild(sprite, 1);
关于android - 无法添加 Sprite onTouch - Cocos2d-x,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22265614/