Unity基本脚本2

代码1,让小车朝着小红旗移动

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Script4 : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        //游戏开始,让当前游戏物体(即小车)转向另一个游戏物体(即红旗)
        GameObject carObj = GameObject.Find("红旗");//找到名为“红旗”的游戏物体
        this.gameObject.transform.LookAt(carObj.transform);//看向某个游戏物体(即让物体的Z轴指向这个物体)
    }

    // Update is called once per frame
    void Update()
    {
        MoveTo1();//沿着本地坐标系的Z轴移动
    }

    /// <summary>
    /// 沿着本地坐标系的Z轴移动
    /// </summary>
    private void MoveTo1()
    {
        float speed = 3;//每秒移动3米,即速度为3米/秒
        float distance = speed * Time.deltaTime;//速度*时间 == 应该移动到的位置

        transform.Translate(0, 0, distance, Space.Self);//沿着本地坐标系的Z轴移动,会和红旗相碰,但不会停下
    }
}

代码2,向量测距

    /// <summary>
    /// 计算汽车和红旗的距离
    /// </summary>
    private void ComputeDistance()
    {
        Vector3 p1 = GameObject.Find("红旗").transform.position;//红旗的transform
        Vector3 p2 = this.gameObject.transform.position;//汽车的transform

        Vector3 v3 = p2 - p1;
        float distance = v3.magnitude;//2个向量之间的距离,直接调用自带的API就可获取到

        Debug.Log("初始距离为" + distance);
    }

  菜单:Edit/Lock View to Selected 视图跟着选定的物体移动

 

posted @ 2023-07-12 09:28  牛大胆V5  阅读(19)  评论(0)    收藏  举报