You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity中点击3D物体时将相机平移至该物体的实现与脚本修复方法

问题原因

现有脚本没有做3D物体碰撞检测,只要点击鼠标就会基于地面平面计算目标位置移动相机,和脚本挂载的物体没有关联。

修复方案

首先确保所有可点击的3D物体都已经挂载Collider组件(如Mesh Collider、Box Collider等,无需特殊设置),再替换为以下修改后的代码:

using UnityEngine;

public class CamTest : MonoBehaviour {
    // 可在Inspector面板手动指定要控制的相机,未指定则默认取场景主相机
    public Camera targetCam;
    Vector3 groundCamOffset;
    Vector3 camTarget;
    Vector3 camSmoothDampV;

    private Vector3 GetWorldPosAtViewportPoint(float vx, float vy) {
        Ray worldRay = targetCam.ViewportPointToRay(new Vector3(vx, vy, 0));
        Plane groundPlane = new Plane(Vector3.up, Vector3.zero);
        float distanceToGround;
        groundPlane.Raycast(worldRay, out distanceToGround);
        Debug.Log("distance to ground:" + distanceToGround);
        return worldRay.GetPoint(distanceToGround);
    }

    void Start() {
        if (targetCam == null) targetCam = Camera.main;
        Vector3 groundPos = GetWorldPosAtViewportPoint(0.5f, 0.5f);
        Debug.Log("groundPos: " + groundPos);
        groundCamOffset = targetCam.transform.position - groundPos;
        camTarget = targetCam.transform.position;
    }

    void Update() {
        if (Input.GetMouseButtonDown(0)) {
            // 从鼠标位置发射射线检测3D物体碰撞
            Ray clickRay = targetCam.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(clickRay, out RaycastHit hitInfo)) {
                // 仅当射线命中当前脚本挂载的物体时,才触发相机移动
                if (hitInfo.collider.gameObject == gameObject) {
                    float mouseX = Input.mousePosition.x / targetCam.pixelWidth;
                    float mouseY = Input.mousePosition.y / targetCam.pixelHeight;
                    Vector3 clickPt = GetWorldPosAtViewportPoint(mouseX, mouseY);
                    camTarget = clickPt + groundCamOffset;
                    
                    // 若不需要对齐地面点击位置,只想移动到物体中心,可替换为以下代码:
                    // camTarget = transform.position + groundCamOffset;
                }
            }
        }

        // 原有平滑移动逻辑保留
        targetCam.transform.position = Vector3.SmoothDamp(
            targetCam.transform.position, camTarget, ref camSmoothDampV, 0.5f);
    }
}

注意事项

  • 将修改后的脚本挂载到所有需要点击触发相机移动的3D物体上
  • 可按需调整Vector3.SmoothDamp的第四个参数,数值越小相机移动速度越快,越大移动越平缓
  • 如果你的地面不是Y轴为法线、位于原点的平面,需要修改GetWorldPosAtViewportPoint方法里groundPlane的构造参数

内容的提问来源于stack exchange,提问作者Savad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 05:39:05