Unity 3D基础——计算两个物体之间的距离

1.在场景中新建两个 Cube 立方体,在 Scene 视图中将两个 Cude的位置错开。

2.新建 C# 脚本 Distance.cs(写完记得保存)

cs 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Distance : MonoBehaviour
{

    public Transform objTrans1;  //定义两个 Transform 组件变量
    public Transform objTrans2;

    // Start is called before the first frame update
    void Start()
    {
        //计算两个物体距离,使用 Vector3.Distance()
        float dis = Vector3.Distance(objTrans1.position, objTrans2.position);
        //输出到控制台
        Debug.Log("Distance = " + dis);
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

3.将脚本绑定到场景中的主相机 Main Camera (将脚本拖到主相机上);然后将 Cube 和 Cube(1) 拖到主相机 Inspector 视图中的 Obj Trans 1 和 Obj Trans 2 中。

4.点击播放按钮,可以在 Console 视图中输出两个 Cube之间的距离(没有 Console 窗口按 Ctrl+Shift+C)

相关推荐
LONGZETECH1 小时前
无人机实训高成本痛点解法:虚拟仿真实现 70% 耗材损耗下降
大数据·算法·unity·架构·无人机
在下胡三汉2 小时前
GLTF vs OBJ vs FBX vs GLB:选择合适的 3D 文件格式,怎么获取下载
3d
fanfan_hongyun2 小时前
Cesium for unity (可加载3dTileset)
3d
鲲穹AI种草3 小时前
家装设计工具记录:多款室内 3D 设计工具能力边界整理
3d·家装设计工具
五仁烧饼14 小时前
Unity Addressables 静默资源策略
游戏·unity·addressables
杀生丸学AI15 小时前
【前馈三维重建】SAF3R:前馈式3D重建Transformer的动态稀疏注意力(加速)
深度学习·3d·transformer
2601_9507607917 小时前
3D细胞活力检测技术:从传统方法到三维体系的跨越
人工智能·3d·蛋白
ue星空21 小时前
【Godot】更换编辑器外观主题
编辑器·游戏引擎·godot
fanfan_hongyun1 天前
unity 与cad 坐标系映射
unity·游戏引擎
牛企老板俱乐部1 天前
广东手板3D打印三大核心产区 采购视角看珠海深圳东莞
3d