mouse and terrain

Jun 4, 2011 at 1:56 PM

Where can i find method that will tell me vector position on heightmap when i have mouse coordinates available?

I was thinking that heightmap.GetPosition(x,y) is for this purpose but it looks like it is meant for something else. Any help?

Coordinator
Jun 4, 2011 at 2:10 PM

Yes, heightmap.GetPosition(x, y) is for getting position from heightmap segment index.

To get a position from heightmap, you can use the following helper method:

        private bool TryGetSurfacePositionFromScreenCoordinate(GraphicsDevice graphics, DrawableSurface surface, int x, int y, Matrix view, Matrix projection, out Vector3 position)
        {
            position = Vector3.Zero;
            Ray pickRay = GraphicsDevice.Viewport.CreatePickRay(x, y, view, projection);
            float? distance = surface.Intersects(pickRay);
            if (distance == null)
                return false;
            position = pickRay.Position + pickRay.Direction * distance.Value;
            return true;
        }
Basically it creates a ray from the screen and performs an intersection test against the surface.
Hope this helps.
Jun 4, 2011 at 2:58 PM

Thanx for fast reply. It works! :)

When i press mouse button line is drawn to correct point at terrain. But now i have question how to convert this vector to terrain coordinates? It seems there is only function that returns vector when i have coordinates . How to do this in opposite direction?

Im trying to modify terrain example and i think that would help others too if there could be added by default this function that displays coordinates and vector on mouse click .

Something like there http://xnaterrain.codeplex.com/

 

I was trying to find a solution in isles code but i found that there is much more complicated solution. And since i mentioned this, what happend to isles 1.0 release download link? I can download only first 12mb and connection is lost. But i could download full source of 52mb without problems. Too bad i cant compile this because i have vs 2010 and xna 4.0. version 3.0 doesnt seem to compile for me so i cant see how this game runs.

Coordinator
Jun 5, 2011 at 2:19 AM

You should use DrawableSurface instead of Heightmap.

The above function returns a position in world space, you can convert it to terrain local space using "position - terrain.Position" because you cannot scale or rotate the terrain. If you are looking for the 2d terrain coordinates, just take the x, y component and ignore the z value, (Z represents up/height in our coordinate system). I have added the above pick method and will check it in later.

There might be some issues with codeplex so the download link might not work, I'll look into it.