团结:我如何找到一个远离玩家和通过鼠标的单位相机的点?

时间:2017-12-29 23:38:57

标签: c# unity3d distance

我想根据鼠标相对于播放器的位置将相机设置为距离播放器7.5f单位。

警告: 在您回答问题或留下回复之前,我要求您查看我在问题结尾处放置的图片,以便您了解我的情况要求。这是一个图表,其中"点A"是相机应该在哪里。例如,""这意味着它是鼠标,播放器和相机结果的一个例子。

我找到了鼠标和播放器之间的距离:

//Distance: mouse -> player
D1 = Mathf.Sqrt(Mathf.Pow(mousePos.x - player.transform.position.x, 2) 
    + Mathf.Pow(mousePos.z - player.transform.position.z, 2));

我设置了将找到鼠标和播放器之间关系的语句:

if(mousePos.x - player.transform.position.x >= 0)
{
    CamX = //Put Code Here
}
if (mousePos.x - player.transform.position.x <= 0)
{
    CamX = //Put code Here
}
if (mousePos.z - player.transform.position.z >= 0)
{
    CamZ = //Put Code Here
}
if (mousePos.z - player.transform.position.z <= 0)
{
    CamZ = //Put Code Here
}

以下是我正在使用的变量:

private float D1;
private float D2;
private float D3;
private float CamX;
private float CamZ;

以下是我正在处理的代码部分。不要接受它,因为我的全部工作仅仅是代码的头脑风暴:

ray = Camera.main.ScreenPointToRay(Input.mousePosition);

if (Physics.Raycast(ray, out hit))
{
    mousePos = new Vector3(hit.point.x, 0.8f, hit.point.z);
    //Distance: mouse -> player
    D1 = Mathf.Sqrt(Mathf.Pow(mousePos.x - player.transform.position.x, 2) 
        + Mathf.Pow(mousePos.z - player.transform.position.z, 2));

    if(mousePos.x - player.transform.position.x >= 0)
    {
        CamX = //Put Code Here
    }
    if (mousePos.x - player.transform.position.x <= 0)
    {
        CamX = //Put code Here
    }
    if (mousePos.z - player.transform.position.z >= 0)
    {
        CamZ = //Put Code Here
    }
    if (mousePos.z - player.transform.position.z <= 0)
    {
        CamZ = //Put Code Here
    }
    //Distance: mouse -> camera
    D2 = D1 + 7.5f;
    //Distance: player -> camera
    D3 = Mathf.Sqrt(Mathf.Pow(player.transform.position.x - CamX, 2)
        + Mathf.Pow(player.transform.position.z - CamZ, 2));
    ...

我的图表

这是一张图片,说明了我希望如何定位所有内容: Expected Result

我的问题是:

如何找到距离播放器7.5f单位的相机位置(点(CamX,CamZ))并通过鼠标坐标(point(mousePosX,mousePosZ))。

1 个答案:

答案 0 :(得分:0)

你可以采取不同的方式,但一种方法是将方向向量从鼠标移动到玩家位置,然后将其添加到你的玩家位置乘以7.5 这里有一些示例代码:

    // assuming Y is the same for player and mouse
    Vector3 normDirection = ((Vector3)playerPos - (Vector3)mousePos).normalized; // unit vector from mouse to player
    Vector2 extendedDir = new Vector2(normDirection.x * 7.5f, normDirection.z * 7.5f);
    Vector2 cameraPos = new Vector2(playerPos.x + extendedDir.x, playerPos.z + extendedDir.y); // extended vector added to player pos

    Camera.main.transform.position = new Vector3(cameraPos.x, .8f, cameraPos.y); // set camera position