unity--一个移动的物体距离一个静止的物体之间的距离测量与显示其距离

在一些情况下需要了解一个移动的物体与一个静止的物体之间的距离
直接上代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class move : MonoBehaviour
{
    public Transform start;
    public Transform end;
    public float speed;
    public Vector3 CUBCoordinate;
    public Vector3 cubmpvecoordinate;
    GameObject gameobgect;
    // Use this for initialization
    void Start()
    {
        gameobgect = GameObject.Find("Cube (1)");
        CUBCoordinate = gameobgect.transform.position;
    }
    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey(KeyCode.L))
        {
            transform.position = Vector3.MoveTowards(start.position, end.position, speed * Time.deltaTime);
            cubmpvecoordinate = transform.position;
        }
    }
    void OnGUI()
    {
        Vector3 sss = cubmpvecoordinate - CUBCoordinate;
        double distance = Math.Sqrt (Math.Pow(sss.x, 2) + Math.Pow(sss.y, 2) + Math.Pow(sss.z, 2));
      //  distance = distance / (double)100;
        GUILayout.Label("当前距离:" + distance.ToString("00.0000000"));
    }
}
实时显示移动物体与静止物体之间的距离,按L键之后物体会匀速运动。

猜你喜欢

转载自blog.csdn.net/wuyiduer/article/details/80488607