开发者

How do I work out which object is nearest the camera?

I'm working on Depth of Field, and I would like to make it more intelligent. Currently, everything is working, but I was wondering how I can automatically adjust dependant on whether the object that the camera is looking at is near or far away?

I first saw this effect in the Unreal en开发者_如何学Cgine, but can't find any resources on how they have done this. Any help will be greatly appreciated.


Just multiply the world position of each object by the camera view matrix and compare the z values of the transformed positions.

EDIT:

Well let's say each of your objects has a world position property 'Position', and assuming you have the camera view matrix, the code should look something like this:

public static MyObject FindClosest(List<MyObject> visibleObjects, Matrix cameraViewMatrix)
  {
     MyObject closest = null;

     // objects near the camera will be at small negative distances, with the distance becoming more negative as they get farther away
     float closestDistance = float.NegativeInfinity;

     foreach (MyObject o in visibleObjects)
     {
        Vector3 transformed = Vector3.Transform(o.Position, cameraViewMatrix);

        if (transformed.Z > closestDistance)
        {
           closestDistance = transformed.Z;
           closest = o;
        }
     }

     return closest;
  }

Note that you should only pass visible objects to this function (objects actually inside the view frustum). Points near the camera in view space will have small negative z-values that become more negative as you move away from the camera. If you were to test an object that was behind the camera it would have a positive z-value and as far as this code is concerned it would be closer than all the objects actually in front of the camera.


The most common way of doing this is to transform the world into camera space (ie, positions and orientations are relative to the camera), and then distance from the camera is simply their Z position (assuming standard Left-Handed Cartesian Coordinates). Now, every camera has a focal length. This is the distance at which objects appear sharpest. How far an object is from this focal 'sweet spot' determines how much blur it gets.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜