return 相机到游戏对象的 C# 脚本

C# script to return camera to a gameobject

在 Unity 中,我有一个相机作为 2D 游戏对象的子项(跟随它)。有一个 IF 语句,可以让我通过按住一个键将相机向前移动。在我放手后,我需要一个代码 return 相机回到游戏对象。谢谢你的帮助。

public class camera : MonoBehaviour
{
    public float panspeed = 30f;
    public float panBorderThickness = 30f;
    public GameObject ship1;
    private Vector3 offset;
    

    void Update()
    {
        if (Input.GetKey("f"))
        {
            Vector3 pos = transform.position;
            if (Input.mousePosition.y >= Screen.height - panBorderThickness)
            {
                pos.y += panspeed * Time.deltaTime;
            }
            if (Input.mousePosition.y <= panBorderThickness)
            {
                pos.y -= panspeed * Time.deltaTime;
            }
            if (Input.mousePosition.x >= Screen.width - panBorderThickness)
            {
                pos.x += panspeed * Time.deltaTime;
            }
            if (Input.mousePosition.x <= panBorderThickness)
            {
                pos.x -= panspeed * Time.deltaTime;
            }
            transform.position = pos;
        }
        //something to return the camera back when i let go of F key
    }
}
if(Input.GetKeyUp("f")){
    transform.position = ship1.transform.position;
}

旁注,您不能只为向量的一个分量赋值。您需要将具有新组件或 add/subtract 的整个向量重新分配给原始向量。你的脚本应该看起来像

if (Input.GetKey("f"))
{
    Vector3 pos = transform.position;
    if (Input.mousePosition.y >= Screen.height - panBorderThickness)
    {
        pos += new Vector3(0, panspeed * Time.deltaTime, 0);
    }
    if (Input.mousePosition.y <= panBorderThickness)
    {
        pos -= new Vector3(0, panspeed * Time.deltaTime, 0);
    }
    if (Input.mousePosition.x >= Screen.width - panBorderThickness)
    {
        pos += new Vector3(panspeed * Time.deltaTime, 0, 0);
    }
    if (Input.mousePosition.x <= panBorderThickness)
    {
        pos -= new Vector3(panspeed * Time.deltaTime, 0, 0);
    }
    transform.position = pos;
}

if(Input.GetKeyUp("f"))
{
    transform.position = GameObjectYouWant.transform.position;
}

如果我没理解错的话,你会想要平滑地将相机移回原来的位置,所以我可能会这样做

private void Update ()
{
    if (Input.GetKey(KeyCode.F))
    {
        var pos = transform.position;
        if (Input.mousePosition.y >= Screen.height - panBorderThickness)
        {
            pos.y += panspeed * Time.deltaTime;
        }
        if (Input.mousePosition.y <= panBorderThickness)
        {
            pos.y -= panspeed * Time.deltaTime;
        }
        if (Input.mousePosition.x >= Screen.width - panBorderThickness)
        {
            pos.x += panspeed * Time.deltaTime;
        }
        if (Input.mousePosition.x <= panBorderThickness)
        {
            pos.x -= panspeed * Time.deltaTime;
        }
        transform.position = pos;
    }
    else
    {
        transform.position = Vector3.MoveTowards(transform.position, ship1.transform.position - ship1.transform.forward * 10, panspeed * Time.deltaTime);
    }
}