我正在尝试将相机移动到具有指定偏移量的单击的Gameobjects位置。因此,脚本应该通过单击的游戏对象位置,实际摄像机位置和偏移量来计算结果位置。
我已经用以下代码尝试过:
Vector3 distanceVector = transform.position - target.transform.position;
Vector3 distanceVectorNormalized = distanceVector.normalized;
targetPosition = (distanceVectorNormalized * preferredDistance);
但是我得到了一些非常奇怪的价值观。这是我为此编写的代码:
public float moveSpeed = 0.1f;
private bool moving = false;
private GameObject target;
// The distance between the camera and the targets position
private float preferredDistance = 3;
// The position the camera will move to
private Vector3 targetPosition;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out var hit, 100) == false) return;
Debug.Log(hit.transform.gameObject.name);
target = hit.transform.gameObject;
... Here should be the calculations
moving = true;
}
if (moving)
{
transform.position = Vector3.Lerp(transform.position, targetPosition, moveSpeed);
transform.LookAt(target.transform.position);
var offsetX = Math.Abs(transform.position.x - targetPosition.x);
var offsetZ = Math.Abs(transform.position.z - targetPosition.z);
if (offsetX < .01
&& offsetZ < .01) moving = false;
}
}
答案 0 :(得分:2)
您的归一化distanceVector
充当照相机朝向对象的方向。
您应该对此方向进行归一化,以便您将其乘以preferredDistance
。然后,它成为摄影机与目标的偏移。
出现问题的部分是,您将此 normalized 偏移设置为新的相机位置,而应将其添加到其中:
Vector3 distanceVector = transform.position - target.transform.position;
Vector3 distanceVectorNormalized = distanceVector.normalized;
targetPosition = target.transform.position + (distanceVectorNormalized * preferredDistance);
请注意最后一行的区别。