0
点赞
收藏
分享

微信扫一扫

敦煌文化主题页面 HTML,CSS,Javascript 源码分享

艾晓雪 2024-08-04 阅读 47

Unity3D功能开发入门系列(三)

一、运动脚本

(一)物体的运动

一般使用 transform.Translate( ),实现相对运动
transform.Translate( dx, dy, dz, …) ,其中 dx, dy, dz 是坐标增量

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

public class MoveLogic : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        float speed = 1;
        float distance = speed * Time.deltaTime;

        //Vector3 pos = this.transform.localPosition;
        //pos.z += distance; // 0.005f;
        //this.transform.localPosition = pos;

        this.transform.Translate(distance, 0, distance);
    }
}

在这里插入图片描述

(二)相对运动

transform.Translate( dx, dy, dz, space),其中第 4 个参数:

  • Space.World,相对于 世界坐标系
    在这里插入图片描述

  • Space.Self,相对于 自身坐标系(本地坐标系)<更常用>
    在这里插入图片描述

(三)运动的方向

使物体朝着目标方向移动(这里以小红旗为例),到达目标后停下来
在这里插入图片描述
在这里插入图片描述

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using static Unity.IO.LowLevel.Unsafe.AsyncReadManagerMetrics;

public class MoveLogic : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        // 获取目标物体
        GameObject flag = GameObject.Find("红旗");
        // 转向目标
        this.transform.LookAt(flag.transform);
    }

    // Update is called once per frame
    void Update()
    {
        GameObject flag = GameObject.Find("红旗");
        Vector3 p1 = this.transform.position;
        Vector3 p2 = flag.transform.position;
        Vector3 p = p2 - p1;
        float distance = p.magnitude; // magnitude 取向量的模

        if(distance > 0.3f)
        {
            float speed = 2;
            float move = speed * Time.deltaTime;
            this.transform.Translate(0, 0, move, Space.Self);
        }
    }
}


二、旋转脚本

(一)物体的旋转

给物体调转一个旋转的角度

  • Quaternion 四元组(x, y, z, w)
    transform.rotation = … 不便操作,官方也不建议使用
  • 欧拉角 Euler Angle
    transform.eulerAngles = new Vector3( 0, 45, 0);
    transform.localEulerAngles = new Vector( 0, 45, 0);
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RotateLogic : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        Application.targetFrameRate = 60;
    }

    // Update is called once per frame
    void Update()
    {
        float rotateSpeed = 60; // 每秒转 60°

        Vector3 angles = this.transform.localEulerAngles;
        angles.y += rotateSpeed * Time.deltaTime; //0.5f;
        this.transform.localEulerAngles = angles;
    }
}

在这里插入图片描述

(二)相对旋转

Rotate( ),旋转一个相对角度
transform.Rotate( dx, dy, dz, space)

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

public class RotateLogic : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        Application.targetFrameRate = 60;
    }

    // Update is called once per frame
    void Update()
    {
        float rotateSpeed = 60; // 每秒转 60°

        //Vector3 angles = this.transform.localEulerAngles;
        //angles.y += rotateSpeed * Time.deltaTime; //0.5f;
        //this.transform.localEulerAngles = angles;

        this.transform.Rotate(0, rotateSpeed * Time.deltaTime, 0, Space.Self);
    }
}

(三)自传与公转

  • 自转,绕着自身轴旋转
  • 公转,围绕另一个物体旋转

在这里插入图片描述

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

/** 此脚本挂在卫星上
 * 
 */
public class MoonLogic : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        float rotateSpeed = 60;

        // 找到父物体
        Transform parent = this.transform.parent;

        // 控制父物体旋转
        parent.Rotate(0, rotateSpeed* Time.deltaTime, 0, Space.Self);
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/** 地球运动的脚本
 * 
 */
public class PlanetLogic : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        float rotateSpeed = 10; 

        this.transform.Rotate(0, rotateSpeed * Time.deltaTime, 0, Space.Self);
    }
}

在这里插入图片描述

(四)官方文档

手册 Manual + Script API:https://docs.unity.cn/cn/2022.3/ScriptReference/index.html


三、脚本的运行

(一)脚本的运行

Unity 是一款游戏引擎,用于驱动游戏逻辑
(1)场景的加载过程(伪代码)

注:Unity 是一个纯面向对象的框架,对象由框架创建

(2)再添加一个物体,也挂载相同的 SimpleLogic 脚本(伪代码)

其中,又创建了一个 SimpleLogic 实例,挂在了新的节点下

(二)消息函数

所有的脚本,一般应继承于 MonoBehavour消息函数,或称 事件函数,一些回调函数

常见的消息函数:

函数说明
Awake初始化,仅执行一次
Start初始化,仅执行一次
Update帧更新,每帧调用一次
OnEnable每当组件启用时调用
OnDisable每当组件禁用时调用

(三)脚本执行顺序

Unity 默认是单线程的协程异步
1. 消息函数的调用顺序:
第1阶段初始化:script1.Awake( ),script2.Awake( ),…
第2阶段初始化:script1.Start( ),script2.Start( ),…
帧更新:script1.Update( ),script2.Update( ),…

2. 脚本优先级 Script Execution Order
默认的,所以脚本的优先级为0,无特定顺序(执行顺序和在 Hierarchy 中的顺序无关)

一般的,并不需要显示设置 Execution Order,默认即可

(四)主控脚本

主控脚本,即游戏的主控逻辑,设置一些全局性的设置、全局性的逻辑,其他的脚本就只用负责各种的功能了
在这里插入图片描述


四、脚本的参数

(一)脚本的参数

脚本的参数,用于控制脚本组件的功能
在这里插入图片描述
添加下面这行代码到 RotateLogic 的全局中后:

public float rotateSpeed = 30f;

在这里插入图片描述

[Tooltip("这个是Y轴向的角速度")]
public float rotateSpeed = 30f;

这样同一个脚本就可以在多个物体上使用,其相关参数可以通过检查器调节

(二)参数的赋值

以下按时间顺序:

  1. 定义默认值 public float rotateSpeed = 30f;
  2. 检查器中赋值 script.rotateSpeed = 180f; // 由 Unity 框架对参数赋值
  3. 在 Awake 中初始化
  4. 在 Start 中初始化
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RotateLogic : MonoBehaviour
{
    [Tooltip("这个是Y轴向的角速度")]
    public float rotateSpeed = 30f;

    private void Awake()
    {
        this.rotateSpeed = 90;
        Debug.Log("** Awake , rotateSpeed=" + this.rotateSpeed);
    }
   
    void Start()
    {
        this.rotateSpeed = 120;
        Debug.Log("** Start , rotateSpeed=" + this.rotateSpeed);
    }

    void Update()
    {
        // float speed = 30f; // 每秒转
        Debug.Log("** 速度=" + this.rotateSpeed);
        this.transform.Rotate(0, rotateSpeed * Time.deltaTime, 0, Space.Self);
    }

}

(三)值类型

参数的类型,分为 值类型(栈上)、引用类型(堆上)
值类型,如 int,float,bool
值类型 (struct) ,如 Vector3,Color
引用类型 (class) ,如 GameObject,Transform,MeshRendered

  1. 值类型的特点:
  • 本身是一个值,可以直接赋值
  • 若为赋值,则默认为 0
  • 不能为 null
  1. 结构体 struct,也是值类型(特点与1同)
    设初始值要new eg. public Vector3 rotateSpeed = new Vector3(1, 1, 1)

(四)引用类型

参数也可以是引用类型

  • 节点,GameObject
  • 组件,如 Transform、MeshRenderer、AudioSourse …
  • 资源,如 Material、Texture、AudioClip
  • 数组类型
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TrainLogic : MonoBehaviour
{
    public GameObject target;
    
    void Start()
    {
        Application.targetFrameRate = 60;

        this.transform.LookAt(target.transform);
    }

    void Update()
    {
        Vector3 p1 = this.transform.position;
        Vector3 p2 = target.transform.position;
        Vector3 p = p2 - p1;
        float distance = p.magnitude;

        if(distance > 0.3f)
        {
            float speed = 2;
            float move = speed * Time.deltaTime;
            this.transform.Translate( 0, 0, move, Space.Self);
        }
    }
}

在这里插入图片描述

(五)运行时调试

在游戏运行时,可以对 物体 / 组件 进行 实时调试,但是在运行模式下,所有的参数不能保存到场景。保存参数的办法:

  • Play Mode 下,暂停一下游戏,组件 Copy Component
  • Edit Mode 下,组件 Paste Component Values
    在这里插入图片描述

五、鼠标键盘输入

(一)鼠标输入

游戏的输入,可以来自鼠标、键盘、触摸屏、游戏手柄

鼠标输入相关 API:

指令含义
Input.GetMouseButtonDown( )探测用户是否按下鼠标
Input.GetMouseButtonUp( )探测用户是否抬起鼠标
Input.GetMouseButton( )状态探测,探测用户是否一直按着鼠标

1. 事件探测

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

public class FanLogic : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            Debug.Log("** 鼠标按下");
        }
        if(Input.GetMouseButtonUp(0))
        {
            Debug.Log("** 鼠标抬起");
        }
        
        float speed = 180;
        this.transform.Rotate(0, speed * Time.deltaTime, 0, Space.Self);
    }
}

在这里插入图片描述

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

public class FanLogic : MonoBehaviour
{
    float m_speed = 0;
    
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            Debug.Log("** 鼠标按下");
            m_speed = 180;
        }
        if(Input.GetMouseButtonUp(0))
        {
            Debug.Log("** 鼠标抬起");
            m_speed = 0;
        }
        
        // float speed = 180;
        this.transform.Rotate(0, m_speed * Time.deltaTime, 0, Space.Self);
    }
}

2. 状态探测

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

public class FanLogic : MonoBehaviour
{
    float m_speed = 0;
    
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if(Input.GetMouseButton(0))
        {
            Debug.Log("** 鼠标按下ing,正被按下");
            m_speed = 180;
        }
        else
        {
            m_speed = 0;
        }
        
        // float speed = 180;
        this.transform.Rotate(0, m_speed * Time.deltaTime, 0, Space.Self);
    }
}

在这里插入图片描述

(二)屏幕坐标

1. 鼠标按下时,取得鼠标的当前所在位置(其中,mousePosition 是鼠标在屏幕上的坐标):
在这里插入图片描述

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

public class CubeLogic : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        int width = Screen.width;
        int height = Screen.height;
        Debug.Log("** 屏幕 : " + width + ", " + height);
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Vector3 mousePos = Input.mousePosition;
            Debug.Log("** 鼠标位置" + mousePos);
        }
    }
}

在这里插入图片描述
2. 一个物体,在屏幕上的位置
其中所谓 屏幕,相对于摄像机而言的,实际上是指摄像头的屏

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

public class CubeLogic : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        //int width = Screen.width;
        //int height = Screen.height;
        //Debug.Log("** 屏幕 : " + width + ", " + height);

        Vector3 pos = this.transform.position;
        Vector3 screenPos = Camera.main.WorldToScreenPoint(pos);
        Debug.Log("** 物体的屏幕坐标:" + screenPos);
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Vector3 mousePos = Input.mousePosition;
            Debug.Log("** 鼠标位置" + mousePos);
        }
    }
}

在这里插入图片描述

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

public class CubeLogic : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        //int width = Screen.width;
        //int height = Screen.height;
        //Debug.Log("** 屏幕 : " + width + ", " + height);

        Vector3 pos = this.transform.position;
        Vector3 screenPos = Camera.main.WorldToScreenPoint(pos);
        Debug.Log("** 物体的屏幕坐标:" + screenPos);
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Vector3 mousePos = Input.mousePosition;
            Debug.Log("** 鼠标位置" + mousePos);
        }

        Vector3 pos = this.transform.position;
        Vector3 screenPos = Camera.main.WorldToScreenPoint(pos);
        if(screenPos.x < 0 || screenPos.x > Screen.width)
        {
            Debug.Log("** 物体已出屏幕边界");
        }

        float speed = 4;

        transform.Translate(speed*Time.deltaTime, 0, 0, Space.World);
    }
}

在这里插入图片描述

(三)键盘输入

相关 API:

指令解释
Input.GetKeyDown( key )按键事件,按下
Input.GetKeyUp( key )按键事件,抬起
Input.GetKey( key )按键状态,是否正被按下
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FlyLogic : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        float zSpeed = 0;
        if(Input.GetKey(KeyCode.W))
        {
            // Debug.Log("* 按键 w 被按下");
            zSpeed = 1;
        }    
        this.transform.Translate(0, 0, zSpeed * Time.deltaTime, Space.Self);
    }
}


举报

相关推荐

0 条评论