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)

相关推荐
魔士于安5 分钟前
unity 卡通风整套资源 小鸟N套带动作+一套卡通风村落 和 相关道具+落叶粒子效果 buildin
游戏·unity·游戏引擎·贴图·模型
AI前沿资讯1 小时前
支持视频动作迁移的AI 3D平台有哪些?2026全维度测评
人工智能·3d
CG_MAGIC1 小时前
幕后花絮:用Blender打造自己的建筑
3d·blender·贴图·uv·建模教程·渲云渲染
伽蓝_游戏1 小时前
第一章:解构游戏资源
游戏·unity·性能优化·c#·游戏引擎·游戏程序·assetbundle
星辰徐哥2 小时前
Unity C#入门:Visual Studio与Unity的关联配置
unity·c#·visual studio
Sparkle Star3 小时前
Unity VRTK4包导入和依赖关系
unity·游戏引擎
scott1985123 小时前
3DGUT与3DGRT
3d
WiChP4 小时前
【V0.1B7】从零开始的2D游戏引擎开发之路
游戏引擎
Sparkle Star7 小时前
Unity VRTK4+SteamVR传送组件使用和层级关系
unity·游戏引擎
cheniie7 小时前
Windows下Unity开发VisionPro应用
windows·unity·vision pro