I think that there are two issues:
camera.getPickRay function expects the window position (and not the clicked position) as its argument. So the line for computing the picking ray should be
const ray = viewer.camera.getPickRay(event.position);
An aside: When trying to visualize the clicked point, note that
scene.pickPosition already does return the world position. So you could just visualize that:
position: clickedPoint, // Use clickedPoint here
But your goal seemed to be to actually compute the intersection manually.
2: When you want to compute the intersection between the picking ray and the plane, you have to take the position of the plane into account. Note that the
plane object itself is only a mathematical description of the plane. It is not the object that you see on the screen. The object that you see on the screen is the entity that is created by calling
And this entity uses the
planePosition to compute the visual representation of the plane, oriented properly for that position on the globe.
Or to put it that way: When you compute the
ray, then this refers to what you see on the screen. And one could think that this ray intersects the plane. But it does not really intersect the
plane, but only the visual representation of that plane.
There are different ways to handle this. Generally, you have to make sure that the intersection test that is done with
IntersectionTests.rayPlane takes place in the right space or coordinate system.
One possible solution is:
- Transform the ray into the space of the actual
- Perform the intersection test
- Transform the intersection point back into the space of the visual representation of the plane
I have added this in the following sandcastle. But with a disclaimer: I did not follow all the computations that you did there (and I think that adding the
planePosition and the
worldNormal does not seem to make much sense). And there are certainly easier and more elegant solutions for this. As I said: Maybe you can just use the
clickedPoint directly. You could also try to move the
plane object to the desired space, and add the plane entity at a position of (0,0,0). But this sandcasle shows the solution that I described abve, just to illustrate the maths, and the point of bringing the
ray and the
plane object into the same space.