2011-02-16 73 views
0

在我的程序中我有一個輸入和一個輸出。輸入是一個二維位置,範圍可以從(0,0)到(240,360)。我的輸出是在XNA中生成的3D世界。視野和座標翻譯

但是,我一直無法弄清楚如何將點從2D網格轉換爲3D。我希望能夠對點進行翻譯,以便(X,X)在XNA中顯示相機可以看到的左上角工作點。同樣,我想讓點(240,360)出現在相機可以看到的右下角。 Z值將爲零(它會改變,但這超出了這個問題的範圍)。

我怎樣才能找出我相機的視角在哪裏? 下面是我在3D世界中繪製對象的方法。

 Vector3 camPos = new Vector3(0.0f, 0.0f, 500.0f); 

     Matrix view = Matrix.CreateLookAt(camPos, Vector3.Zero, Vector3.Up); 
     Matrix proj = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, GraphicsDevice.DisplayMode.AspectRatio, 1, 10000); 
     Matrix ballWorld = Matrix.Identity; 

     //rotate it so that it is always facing foward 
     ballWorld.Forward = direction; 
     ballWorld.Up = Vector3.Up; 
     ballWorld.Right = Vector3.Cross(direction, Vector3.Up); 

     foreach (SphereObject so in blobs) { 
      Matrix sphereWorld = ballWorld; 
      sphereWorld *= Matrix.CreateTranslation(so.Position); 
      sphereWorld *= Matrix.CreateScale(so.Scale); 

      so.SphereModel.Draw(sphereWorld, view, proj); 
     } 

這裏的地方我從2D平面的點和創建SphereObject

public void CreateNewBlob(System.Drawing.Point p) { 
     Random rand = new Random(); 

     SphereObject so = new SphereObject(model, new Vector3(p.X, p.Y, 0)); 
     so.SetColor(new Color((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble())); 

     blobs.Add(so); 
    } 

回答

0

怎麼樣的二維點映射到口,然後從這一點unprojecting射線,並用它根據遠剪裁平面找到射線上最遠的可見點?

 float farplane = 1000; 

     Matrix proj = Matrix.CreateLookAt(Vector3.Zero, Vector3.Forward, Vector3.Up); 
     Matrix view = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, this.GraphicsDevice.Viewport.AspectRatio, 1, farplane); 

     Vector2 Coord = new Vector2(10,10);  //between 0,0 and 240,360 

     Coord.X = Coord.X * (GraphicsDevice.Viewport.Width/240); 
     Coord.Y = Coord.Y * (GraphicsDevice.Viewport.Height/360); 

     Ray r = ProjectRayFromPointOnScreen((int)Coord.X, (int)Coord.Y, proj, view); 

     Vector3 ballpos = r.Position + (r.Direction *= (farplane - 1)); //Move just inside the far plane so its not clipped by accident 

    public Ray ProjectRayFromPointOnScreen(int x, int y, Matrix ProjectionMatrix, Matrix ViewMatrix) 
    { 
     Vector3 nearsource = new Vector3(x, y, 0); 
     Vector3 farsource = new Vector3(x, y, 1); 

     /* The Unproject method: http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.viewport.unproject.aspx */ 

     GraphicsDevice graphics = this.GraphicsDevice; 

     Vector3 startpoint = graphics.Viewport.Unproject(nearsource, 
                 ProjectionMatrix, 
                 ViewMatrix, 
                 Matrix.Identity); 
     Vector3 endpoint = graphics.Viewport.Unproject(farsource, 
                 ProjectionMatrix, 
                 ViewMatrix, 
                 Matrix.Identity); 

     Vector3 direction = endpoint - startpoint; 
     direction.Normalize(); 

     Ray r = new Ray(startpoint, direction); 
     return r; 
    } 

這似乎工作,雖然我不知道你的應用程序試圖達到什麼樣的效果。 祝你好運!