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

Unity3D中如何在点击的Mesh(墙体)另一侧生成物体?

Unity点击Mesh在点击位置另一侧生成物体实现方案

实现步骤

1. 射线检测获取点击信息

通过Physics.Raycast从鼠标位置发射射线,捕捉点击的Mesh,拿到点击坐标和该点的法线方向(法线指向Mesh外侧,反方向即为“另一侧”)。如果需要自定义沿X/Y/Z轴生成,可通过参数切换方向。

2. 计算生成位置

  • 基于Mesh法线:生成位置 = 点击点 + (-法线方向) × 偏移距离(偏移值根据生成物体的大小调整,避免和原Mesh重叠)
  • 自定义三轴方向:比如选X轴正方向,生成位置 = 点击点 + Vector3.right × 偏移距离;X轴负方向则用-Vector3.right,Y、Z轴以此类推。

3. 生成物体

用Instantiate在计算好的坐标生成预设物,可选择保持预设自身旋转,或匹配原Mesh的旋转角度。

代码示例

创建C#脚本挂载到主相机(或任意GameObject):

using UnityEngine;

public class SpawnOnMeshClick : MonoBehaviour
{
    // 要生成的物体预设
    public GameObject spawnPrefab;
    // 偏移距离(根据物体大小调整)
    public float offsetDistance = 0.5f;
    // 生成方向选择:0=法线方向,1=X正,2=X负,3=Y正,4=Y负,5=Z正,6=Z负
    public int spawnDirection = 0;

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out RaycastHit hit))
            {
                // 限制仅点击MeshCollider的物体
                if (hit.collider is MeshCollider)
                {
                    Vector3 spawnPos = CalculateSpawnPosition(hit);
                    // 生成物体,这里保持预设旋转,也可改为hit.transform.rotation匹配Mesh角度
                    Instantiate(spawnPrefab, spawnPos, spawnPrefab.transform.rotation);
                }
            }
        }
    }

    Vector3 CalculateSpawnPosition(RaycastHit hit)
    {
        switch (spawnDirection)
        {
            case 1:
                return hit.point + Vector3.right * offsetDistance;
            case 2:
                return hit.point - Vector3.right * offsetDistance;
            case 3:
                return hit.point + Vector3.up * offsetDistance;
            case 4:
                return hit.point - Vector3.up * offsetDistance;
            case 5:
                return hit.point + Vector3.forward * offsetDistance;
            case 6:
                return hit.point - Vector3.forward * offsetDistance;
            default:
                // 默认沿法线反方向生成
                return hit.point + (-hit.normal) * offsetDistance;
        }
    }
}

使用说明

  • 在Inspector面板中,将需要生成的物体预设拖入spawnPrefab字段
  • 调整offsetDistance避免生成物体与原Mesh重叠
  • 通过spawnDirection选择生成方向:0为基于Mesh法线的另一侧,1-6对应X/Y/Z轴的正负方向
  • 确保点击的Mesh添加了MeshCollider(复杂Mesh建议勾选Convex优化检测性能)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 23:24:37