Hi All,
I am trying to make a combat system similar to WoW and want to code spells that have AoE. Right now the camera is in a third person mode, always a few units behind the player and pointing at the player. I want to have the player target a certain area on the ground (which is a 3D terrain) to cast an AoE spell, but I can't figure out the terrain position based on the mouse coordinates. I've searched a lot this morning and have found this code:
| //---------------------------------------------------------------- |
| // GetPickedPosition() - gets 3D position of mouse pointer |
| // - always on the the Y = 0 plane |
| //---------------------------------------------------------------- |
| public static Vector3 GetPickedPosition(Vector2 mousePosition, float nearClip, Matrix projectionMatrix, Matrix viewMatrix) |
| { |
| |
| // create 2 positions in screenspace using the cursor position. 0 is as |
| // close as possible to the camera, 10 is as far away as possible |
| Vector3 nearSource = new Vector3(mousePosition, 0f); |
| Vector3 farSource = new Vector3(mousePosition, nearClip); |
| |
| // find the two screen space positions in world space |
| Vector3 nearPoint = Globals.graphicsDevMgr.GraphicsDevice.Viewport.Unproject(nearSource, |
| chaseCamera.projectionMatrix, |
| chaseCamera.viewMatrix, |
| Matrix.Identity); |
| |
| Vector3 farPoint = Globals.graphicsDevMgr.GraphicsDevice.Viewport.Unproject(farSource, |
| projectionMatrix, |
| viewMatrix, |
| Matrix.Identity); |
| |
| // normalized direction vector from nearPoint to farPoint |
| Vector3 direction = farPoint - nearPoint; |
| direction.Normalize(); |
| |
| // create a ray using nearPoint as the source |
| Ray r = new Ray(nearPoint, direction); |
| |
| // calculate the ray-plane intersection point |
| Vector3 n = new Vector3(0f, 1f, 0f); |
| Plane p = new Plane(n, 0f); |
| |
| // calculate distance of intersection point from r.origin |
| float denominator = Vector3.Dot(p.Normal, r.Direction); |
| float numerator = Vector3.Dot(p.Normal, r.Position) + p.D; |
| float t = -(numerator / denominator); |
| |
| // calculate the picked position on the y = 0 plane |
| Vector3 pickedPosition = nearPoint + direction * t; |
| |
| return pickedPosition; |
| } |
However, this makes several assumptions that I don't think I can use in my game. The code above (designed for an RTS) assumes that everything is on a plane y=0, and that the camera is pointed downwards - like a bird's eye point of view. Does anyone know how to adapt it for a Third person or first person mode, where the objects can be anywhere in 3D space (not necessarily just y = 0)?