Clicking on 3D Objects
I've been following the sample in Help about checking whether a user has clicked a 3D object (Math section) and decided to try it out myself on a cube. I have built the cube, setup up shaders and also the code for drawing a ray between the near and far planes (starting from where the mosue click happened). Then I define a BoundingBox around my cube and check whether the ray intersects the bounding box. Problem is, even when I click outside of the box (not all areas), the ray is intersecting the cube. I am able to rotate my cube with some smple transformations, and I am rotating the bounding box as well. Here's some code:
BoundingBox cubeBB =
new
BoundingBox(topLeftFront, bottomRightBack); //topLeftFront and bottomRightBack are Vector3//world matrixworldMatrix =
Matrix.CreateRotationX((float
)(rotx * (Math.PI / 180))) *Matrix.CreateRotationY((float
)(roty * (Math.PI / 180))) *Matrix.CreateRotationZ((float
)(rotz * (Math.PI / 180)));//update bounding boxcubeBB.Min =
Vector3.Transform(cubeBB.Min, worldMatrix);cubeBB.Max =Vector3.Transform(cubeBB.Max, worldMatrix);
Perhaps someone can shed some light on how to properly use BoundingBoxes? the documentation is a bit lacking, I followed the examples as much as I could.
[1875 byte] By [
killfr0g] at [2007-12-24]
You are transforming cube min and max points. It won't work this way. Just think about what you are doing.
The cubeBB is axis aligned bounding box. If you take topleftFront point and rotate it somehow, It won't be top left front point anymore.
That's the reason why your code can't work.
What do you want probably do is to use two bounding boxes, first one will be untransformed (can even be non axis aligned), the second one will be axis aligned box that you will have to compute properly taking axis of the first box into account, rotating them, and using this information to compute new min and max for the axis aligned box.
Or you can use just one axis aligned bounding box that somehow encapsulates the mesh always no matter how the mesh is rotated (this box is just big cube).
All in all you will probably also want to test the mesh itself, when the box collides with the ray in order to get some usable accuracy.
Of course you can do the object picking other way's also (like rendering all the objects with object ID's instead of colour, and then reading the pixel at given coords to get the ID of the object).
So the BoundingBox is strictly aligned to the axis? It won't do much good here since my cube can be rotated freely. Well I'm not that familiar with 3D techniques, I'm looking at other ways to do it but using the Ray seemed like the quickest way of doing it.
You can use the ray. But you have to use non axis aligned bounding box (and rotate it properly).
Or if it's just a cube you can try to raycast the mesh directly. I'm not sure if in XNA there is a function for it, and I don't have XNA here at this computer. But It definately is in D3DX.