Hi! The cocos2d-x tests have a nice demo showing how to detect touch events on 3D objects in a 2D space (Sprite3DHitTest in tests/cpp-tests/Classes/Sprite3DTest/Sprite3DTest.cpp).
I’m having trouble finding an example that shows how to adapt this to detecting which 3D object is touched in a 3D space. I’d appreciate a point in the right direction, or better yet, some demo code.
Thanks so much!
Erik
I had just found the way how
...
auto listener1 = EventListenerTouchOneByOne::create();
listener1->setSwallowTouches(true);
listener1->onTouchBegan = CC_CALLBACK_2(HelloWorld::onTouchBegan,this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener1, _player);
...
bool HelloWorld::onTouchBegan(cocos2d::Touch* touch, cocos2d::Event* event)
{
// get the Sprite3D
auto target = static_cast<Sprite3D*>(event->getCurrentTarget());
//
// get z position of Sprite3D
float z = target->getPositionZ();
//
// convert rect in 3D screen (camera) TO rect in 2D screen GL
//
//// get boudingbox => rect in 3D screen (camera)
Rect rect = target->getBoundingBox();
//
//// using camera projectGL to get LB point, and RT point in 2D screen from "3D Rect"
Vec2 LeftBottom = _camera->projectGL(Vec3(rect.origin.x, rect.origin.y, z));
Vec2 RightTop = _camera->projectGL(Vec3(rect.origin.x + rect.size.width, rect.origin.y + rect.size.height, z));
//
//// define rect2 from new points (LB and RT)
Rect rect2 = Rect(LeftBottom.x, LeftBottom.y, RightTop.x - LeftBottom.x, RightTop.y - LeftBottom.y);
//
//// location of touch in 2D screen
Point p = touch->getLocation();
//
//// detect p in rect2...
if (rect2.containsPoint( p ))
{
log("sprite3d began... x = %f, y = %f", touch->getLocation().x, touch->getLocation().y);
target->setOpacity(100);
return true;
}
return false;
}
3 Likes