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)

相关推荐
淡海水10 小时前
38-Hybrid生态-LeanCLR总览
unity·架构·c#·热更新·clr·hybrid·leanclr
郝学胜-神的一滴11 小时前
[简化版 GAMES 101] 计算机图形学 13:从光栅化到着色——赋予三维像素光影灵魂
c++·计算机视觉·unity·godot·图形渲染·opengl·unreal
晓131311 小时前
【Cocos Creator 3.x】篇——第五章 项目实战优化技术
前端·javascript·游戏引擎
fqkw612 小时前
unity 安装MCP +uvx
unity·游戏引擎
魔士于安1 天前
unity 音乐会场景 unity2022
游戏·unity·游戏引擎·贴图·模型
一线灵1 天前
Axmol 3.x 输入系统重构:从 Touch/Mouse 到统一 Pointer,再到现代 InputField
重构·游戏引擎
Zwarwolf1 天前
Godot零散知识点项目汇总
游戏引擎·godot
Mediary1 天前
Unity is running with Administrator privileges, which isnot supported...
unity
游乐码1 天前
Unity基础(十四)场景异步加载
unity·游戏引擎
mxwin1 天前
Unity Shader URP:法线在空间变换上的特殊性
unity·游戏引擎·shader