In this tutorial we will populate the scene with a few random objects. Then when the mouse is pressed we compute the ray projected from the mouse click position towards the scene and use it to compute the intersections point. If any intersection is found we highlight the intersection point by moving there a green sphere.
class App_Picking: public BaseDemo
{
public:
{
Camera* camera = rendering()->
as<Rendering>()->camera();
y = openglContext()->height() - y;
Ray ray = camera->computeRay(x,y);
RayIntersector intersector;
intersector.setFrustum( camera->computeRayFrustum( x,y ) );
intersector.intersect(ray, sceneManager());
if (intersector.intersections().size())
{
mIntersectionPoint->setLocalMatrix(
mat4() );
mIntersectionPoint->translate( intersector.intersections()[0]->intersectionPoint() );
mIntersectionPoint->computeWorldMatrix();
Log::print( Say("Intersections detected = %n (%s).\n") << intersector.intersections().size() << intersector.intersections()[0]->actor()->objectName() );
}
else
Log::print("No intersections detected.\n");
}
virtual void initEvent()
{
Log::notify(appletInfo());
int count = 1;
float displace = 2.0f;
for(int z=-count; z<=count; ++z)
for(int y=-count; y<=count; ++y)
for(int x=-count; x<=count; ++x)
{
ref<Effect> fx = new Effect;
fx->shader()->gocLight(0)->setLinearAttenuation(0.025f);
ref<Geometry> geom = randomObject();
Actor* act = sceneManager()->tree()->addActor( geom.get(), fx.get(), new Transform );
act->transform()->translate(x*displace, y*displace, z*displace);
act->transform()->computeWorldMatrix();
}
ref<Effect> fx = new Effect;
fx->shader()->gocLight(0)->setLinearAttenuation(0.025f);
fx->shader()->gocMaterial()->setDiffuse( green );
intersection_point_geom->computeNormals();
Actor* intersection_point_act = sceneManager()->tree()->addActor( intersection_point_geom.get(), fx.get(), new Transform );
mIntersectionPoint = intersection_point_act->transform();
}
ref<Geometry> randomObject()
{
ref<Geometry> geom;
switch(rand() % 7)
{
}
if (!geom->normalArray())
geom->computeNormals();
return geom;
}
protected:
Transform* mIntersectionPoint;
};