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)

相关推荐
大势智慧6 分钟前
DasViewer 4.0 重磅发布,全面增强3DGS处理能力
3d·渲染·应用·效率·实景三维·高斯·成果
jtymyxmz8 分钟前
《Unity Shader》11.3.1 续 流动的水流的阴影
unity·游戏引擎
世洋Blog11 分钟前
Unity性能优化-2d游戏的DrawCall
游戏·unity·面试·性能优化·游戏引擎
YAY_tyy13 分钟前
基于矩形区域的相机自动定位与飞行控制实现
前端·javascript·3d·cesium
jtymyxmz13 分钟前
《Unity Shader》11.2.2 滚动的背景
unity·游戏引擎
Tatalaluola15 分钟前
Unity使用EPPlus读取写入表格
unity·c#·游戏引擎·excel
呆呆敲代码的小Y17 分钟前
【Unity 实用工具篇】 | Unity中的软遮罩组件 SoftMaskForUGUI 快速上手使用
游戏·unity·游戏引擎·免费游戏·遮罩·软遮罩·softmask
思茂信息2 小时前
CST软件对Customer Success OPPO手机电源适配器EMC仿真
开发语言·嵌入式硬件·matlab·3d·智能手机·cst
B0URNE9 小时前
【Unity基础详解】(11)Unity核心:输入系统
unity·游戏引擎
世洋Blog12 小时前
Unity开发微信小游戏-减少WASM包体大小
unity·游戏引擎·wasm·微信小游戏