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)

相关推荐
ysn111111 天前
搭建状态同步框架的实践心得
unity·架构
jinxindeep1 天前
PhysX-Omni:面向刚体、形变体与铰接体的统一仿真就绪 3D 生成
3d
一线灵1 天前
Axmol:小众引擎的硬核逆袭
游戏引擎
weixin_441940011 天前
【Unity教程】使用vuforia创建简单的AR实例
unity·游戏引擎·ar
郝学胜-神的一滴1 天前
[简化版 GAMES 101] 计算机图形学 12:可见性与 Z‑Buffer 深度缓存
unity·godot·图形渲染·three.js·opengl·unreal
归真仙人2 天前
【UE】LineTraceByProfile
ue5·游戏引擎·ue4·unreal engine
游乐码2 天前
Unity基础(十一 )资源同步加载
unity·游戏引擎
LONGZETECH2 天前
汽车仿真教学软件技术实现深度解析:从三维建模到学情数据闭环
c语言·3d·unity·架构·汽车
jinxindeep2 天前
CVPR26最佳论文提名:SAM3D,单图生成可组合3D场景的基础模型
3d
游乐码2 天前
unity基础(九)协程原理
unity·游戏引擎