如何设置相机与缩放对象的距离?

时间:2018-08-30 10:57:14

标签: c# unity3d

我的相机必须聚焦在GameObject上,并且可以随时间缩放。如何计算相机位置,使其始终与此GameObject保持相同的距离?我已经尝试过做

camera.position.y += object.scaleFactor / 2;
camera.position.z -= object.scaleFactor / 2;

但是对象变得越大,其作用就越小。我正在考虑使用边界框,您认为它可以工作吗?

非常感谢!

2 个答案:

答案 0 :(得分:0)

使用此:

// compute this when scale is 1.0f
Vector3 originalPosition = camera.position;
Vector3 originalDistance = camera.position - gameObject.position;

// then use:
camera.position = originalPosition + originalDistance * gameObject.scaleFactor;

如果这不起作用,请更详细地描述您的情况,我将编辑答案

例如:如果您希望相机与物体保持一定距离,则必须使用BoundingSphere.radius

// compute this when scale is 1.0f
Vector3 originalPosition = camera.position;
Vector3 temp = camera.position - gameObject.position;
Vector3 originalDirection = temp.normalized;
float originalDistance = temp.magnitude - boundingSphere.radius;

// use this when object is scaled:
camera.position = originalPosition + originalDirection * (boundingSphere.radius + originalDistance);

答案 1 :(得分:0)

public class ObjectRelativeScale : MonoBehaviour
{
    public float objectScale = 1.0f;
    private Vector3 initialScale;

void Start()
{
    initialScale = transform.localScale;
}

void Update()
{
    Plane plane = new Plane(Camera.main.transform.forward, Camera.main.transform.position);
    float dist = plane.GetDistanceToPoint(transform.position);
    transform.localScale = initialScale * dist * objectScale;
}

}

基本上,方法更好,根据相机位置缩放对象,在此处查看执行情况:

https://gph.is/2Pfpg3g

干杯!