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)

相关推荐
简简单单OnlineZuozuo3 小时前
提示架构:设计可靠、确定性的AI系统
人工智能·unity·架构·游戏引擎·基准测试·the stanford ai·儿童
小宇的天下13 小时前
Calibre 3Dstack --每日一个命令day3【stack】(3-3)
前端·数据库·3d
冥界摄政王13 小时前
CesiumJS学习第四章 替换指定3D建筑模型
3d·vue·html·webgl·js·cesium
微凉的衣柜13 小时前
【3D 打印避坑实录】如何用 Blender 彻底修复空壳 STL
c++·3d·blender
在下胡三汉13 小时前
glTF/glb文件的深入指南下载获取:揭示3D可视化的核心
3d
uniGame1 天前
FrameDebugger使用说明
unity·性能优化
心之所向,自强不息1 天前
URP Shader编程规则之Properties
unity
军军君011 天前
Three.js基础功能学习四:摄像机与阴影
开发语言·前端·javascript·3d·typescript·three·三维
yesyesido1 天前
AI手办工坊:3D渲染级二次元写真生成、多风格角色定制与高清无损下载的一键创作平台
人工智能·3d
Together_CZ1 天前
FlashWorld: High-quality 3D Scene Generation within Seconds——数秒内生成高质量三维场景
3d·generation·3d重建·flashworld·数秒内生成高质量三维场景·3d scene·high-quality