Hey all, I was trying to position a sprite into the center of the scene and getting a touch response on it. But in the output, the sprite is showing in a side of the scene and the area of touch response is also different. I draw a red square on output where I am getting the touch response instead of getting it on the sprite. (v4 & vs2019) .
Here is my code:
AppDelegate.cpp
#include "AppDelegate.h"
#include "TouchScene.h"
USING_NS_CC;
AppDelegate::AppDelegate() {
}
AppDelegate::~AppDelegate()
{
}
bool AppDelegate::applicationDidFinishLaunching() {
auto director = Director::getInstance();
auto glview = director->getOpenGLView();
if (!glview) {
glview = GLViewImpl::create("Hello World");
glview->setFrameSize(640, 480);
director->setOpenGLView(glview);
}
auto scene = TouchScene::createScene();
director->runWithScene(scene);
return true;
}
void AppDelegate::applicationDidEnterBackground() {
}
void AppDelegate::applicationWillEnterForeground() {
}
TouchScene.cpp
#include "TouchScene.h"
USING_NS_CC;
Scene* TouchScene::createScene()
{
auto scene = Scene::create();
auto layer = TouchScene::create();
scene->addChild(layer);
return scene;
}
bool TouchScene::init()
{
if (!Layer::init())
{
return false;
}
auto sprite = Sprite::create("Picture.png");
sprite->setPosition(Vec2(Director::getInstance()->getVisibleSize().width / 2,
Director::getInstance()->getVisibleSize().height / 2));
// Add a "touch" event listener to sprite
auto touchListener = EventListenerTouchOneByOne::create();
touchListener->onTouchBegan = [](Touch* touch, Event* event) -> bool {
auto bounds = event->getCurrentTarget()->getBoundingBox();
if (bounds.containsPoint(touch->getLocation())) {
std::stringstream touchDetails;
touchDetails << "Touched at OpenGL coordinates: " <<
touch->getLocation().x << "," << touch->getLocation().y << std::endl <<
"Touched at UI coordinate: " <<
touch->getLocationInView().x << "," << touch->getLocationInView().y << std::endl <<
"Touched at local coordinate:" <<
event->getCurrentTarget()->convertToNodeSpace(touch->getLocation()).x << "," <<
event->getCurrentTarget()->convertToNodeSpace(touch->getLocation()).y << std::endl <<
"Touch moved by:" << touch->getDelta().x << "," << touch->getDelta().y;
MessageBoxA(0, touchDetails.str().c_str(), "Touched", MB_OK);
}
return true;
};
Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(touchListener, sprite);
this->addChild(sprite, 0);
return true;
}
And here is output:
(red box is not the part of output, i draw it by editing)