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)

相关推荐
一个小狼娃18 小时前
Android集成Unity避坑指南
android·游戏·unity
极客柒18 小时前
Unity 协程GC优化记录
java·unity·游戏引擎
黄思搏18 小时前
Unity SpriteRenderer 进度条 Shader 实现
unity·游戏引擎
猫屋小鱼丸20 小时前
手把手教你在unity中实现一个视觉小说系统(一)
unity
CHOTEST中图仪器1 天前
3d光学轮廓仪如何局部测量标准台阶?
3d·光学轮廓仪·三维形貌·微观尺寸
国服第二切图仔1 天前
Rust开发实战之简单游戏开发(piston游戏引擎)
开发语言·rust·游戏引擎
HahaGiver6661 天前
Unity与Android原生交互开发入门篇 - 打开Unity游戏的设置
android·unity·交互
@LYZY1 天前
Unity TextMeshPro 文本对齐方式详解
unity·游戏引擎·textmeshpro·tmp
在路上看风景1 天前
2.1 ShaderLab - 渲染状态
unity
AA陈超2 天前
虚幻引擎5 GAS开发俯视角RPG游戏 P07-06 能力输入的回调
c++·游戏·ue5·游戏引擎·虚幻