Hi,
I am trying to detect touch in a 3D Sprite and move a 3D child Sprite within it.
for 2D Sprite I am able to move the sprite based on touch using x and y co-ordinates.
How can I get the Z location of touch so that I can move my 3D sprite wherever I touch?
The feature your asking for is called picking and I very much doubt Cocos has implemented it in to the 3d features yet. Basically you will have to do some serious custom coding if you really need it. To pick 3D objects in a scene you need to work with something called raycasting. Every time the “select a 3D object” function is called, you want to create a new ray from the camera position and get a coordinate from the 2D touch coordinate in the viewport space, e.g. where you touched relative to the bottom left corner of the device (0, 0). You can create a ray by performing some calculations with all this data that fires directly from the camera at the location you clicked/touched in the scene. Then you need to search online for some code to to test for collisions between a ray and a 3D bounding box (axis aligned or oobb). Then you need to pass in the bounding box of your cocos 3d model in to this function. You need to find out which was the first object passed through by the ray (you can use the depth buffer values for this, Z-buffer). Basically it’s some real advanced stuff. Put aside a week or something and follow a tutorial if you get stuck.
p.s. 3D objects aren’t sprites.
Hi guys!
Yes, I noticed that it is not very simple.
I have a working solution but if you can improve my code I would be very grateful:
bool containsTouchLocation(cocos2d::Touch* touch)
{
auto location = touch->getLocationInView();
Ray ray;
Vec3 near(location.x, location.y, -1.0f);
Vec3 far(location.x, location.y, 1.0f);
auto size = Director::getInstance()->getWinSize();
// You should get your camera somehow.
camera->unproject(size, &near, &near);
camera->unproject(size, &far, &far);
ray._origin = near;
ray._direction = far - near;
return ray.intersects(this->getAABB());
}
Great! but,what the Ray is?
Like firing a gun, you fire the ray and see if it hits anything, then return what it hits.
You @yixiaoqingyuz should read the programming guid here: http://www.cocos2d-x.org/wiki/3D_Graphics#Ray
Ok,thanks!