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)

相关推荐
试着1 小时前
【数据标注师】3D标注
3d·数据标注师·3d标注
工业3D_大熊9 天前
3D模式格式转换工具HOOPS Exchange如何将3D PDF转换为STEP格式?
3d·pdf·3d格式转换·3d模型格式转换·cad格式转换·cad数据格式转换·3d模型可视化
切韵9 天前
Unity编辑器扩展:UI绑定复制工具
ui·unity·编辑器
广州华锐视点9 天前
浅议 3D 展示技术为线上车展新体验带来的助力
3d
10 天前
Lua复习之何为闭包
开发语言·unity·游戏引擎·lua·交互
深空数字孪生10 天前
2025年小程序地图打车的5大技术革新:实时路况预测与智能调度升级
大数据·人工智能·unity·性能优化·小程序·游戏引擎
RPGMZ10 天前
RPGMZ 游戏引擎如何与lua进行互相调用 初探
开发语言·javascript·游戏引擎·lua·rpgmz
程序猿多布10 天前
Unity Addressable使用之检测更新流程
unity·addressable
Bunny Chen11 天前
Unity中的物理单位是真实的吗?
unity·游戏引擎