unity物体脚本、GameObject控制物体的移动

439 阅读3分钟

一、与物体相关的脚本

1.使用Resources加载Resources中的资源并克隆到场景中

官网 docs.unity.cn/cn/2019.4/S…

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

public class test02 : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        //加载Resource文件夹中的英雄资源
        GameObject hero = Resources.Load<GameObject>("hero/StoneKing");
        //克隆物体到场景中
        GameObject.Instantiate(hero);
    }

}

复制代码

2.查找物体

官网 docs.unity.cn/cn/2019.4/S…

1.通过路径查找物体

//这里举例找到Sphere对象后,停用物体,这样加载场景后就看不到该对象了  
GameObject sphere= GameObject.Find("Sphere");
sphere.SetActive(false);//激活或停用对象
复制代码

2.通过标签查找物体

官网 docs.unity.cn/cn/2019.4/S…

image.png

 GameObject shpere = GameObject.FindGameObjectWithTag("Player");//括号中填标签名
 shpere.SetActive(false); 
复制代码

3.对物体的参数进行改变

官网 docs.unity.cn/cn/2019.4/S…

GameObject shpere = GameObject.FindGameObjectWithTag("Player");//括号中填标签名
//shpere.SetActive(false); 
shpere.name = "sphere01";//修改物体的名字 
shpere.transform.position = new Vector3(0,10,34);//改变世界坐标
shpere.transform.localPosition = new Vector3(0, 10, 34);//改变相对自身起始点的坐标 
shpere.transform.eulerAngles = new Vector3(34,32,1);//改变物体的旋转角度
shpere.transform.localEulerAngles=new Vector3(34, 32, 1);
shpere.transform.localScale = new Vector3(10,10,10);//改变物体的规模大小
复制代码

4.通过脚本删除物体

image.png

5.操作组件的相关脚本

官网 docs.unity.cn/cn/2019.4/S…

 GameObject shpere = GameObject.FindGameObjectWithTag("Player");//括号中填标签名
 shpere.AddComponent<AudioSource>();//添加一个audio source组件  
 GameObject text = GameObject.FindGameObjectWithTag("Text");
 //text.GetComponent<Text>().text="欢迎进入游戏";//查找自身上的Text组件
 //text.GetComponentInChildren<Text>().text = "先查找孩子中是否有该组件再查找自身";
 //text.GetComponentInParent<Text>().text = "先查找父亲中是否有该组件再查找自身";
 //查找多个同类型的组件 
 AudioSource[] audioArray = text.GetComponentsInChildren<AudioSource>();//查找自身挂载的所有音频源组件
 Debug.Log(audioArray.Length);
 //激活和关闭组件  通过组件中的enabled属性,值为false关闭,ture激活
 audioArray[0].enabled = false;
 //可以使用Destory(传入要移除的组件)来移除组件
 Destroy(audioArray[0]);
复制代码

二、像素游戏案例

1.控制虚拟轴移动物体

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

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

    // Update is called once per frame
    void Update()
    {
        //获取水平虚拟轴
        float x = Input.GetAxis("Horizontal");
        //获取垂直虚拟轴
        float z = Input.GetAxis("Vertical");
        Debug.Log($"x:{x},y:{z}");
        //创建一个向量,该向量为玩家按下按键时的向量 
        Vector3 dir = new Vector3(x,0,z);
        //判断玩家是否按下了按键,如果按下按键x,z的值一定会发生变化,这时候向量dir肯定不为0
        if (dir != Vector3.zero)
        {
            //将玩家转dir向量的方向 
            transform.rotation = Quaternion.LookRotation(dir);
            //因为update中是一帧一帧得执行,不同设备在一秒内可能执行的帧数不一样,这里我们想
            //保持每隔一秒移动2m,可以乘以 Time.delta.Time表示每帧经过的时间 
            transform.Translate(Vector3.forward * 2 * Time.deltaTime);
        }
    }
}

复制代码

2.控制摄像机跟随

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

public class cameral : MonoBehaviour
{
    //保存开始时,玩家和相机的向量 
    private Vector3 vector;
    //保存玩家的transform组件 
    private Transform player;
    // Start is called before the first frame update
    void Start()
    {
        //通过标签获取玩家的transform组件
        player = GameObject.FindGameObjectWithTag("Player").transform;
        //获取玩家和相机之间的向量
        vector = player.position - transform.position;

    }

    // Update is called once per frame
    void Update()
    {
        //每次更新相机的位置
        transform.position = player.position - vector;
    }
}

完整代码如下:实现物体在场景中自由的移动

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

public class test01 : MonoBehaviour
{
    //float小数可以斜着走
    private float x;
    private float z;
    // Start is called before the first frame update
    void Start()
    {
        //通过标签名拿到文本对象
        GameObject text = GameObject.FindGameObjectWithTag("text");
        //返回一个Text组件,给textNew进行赋值
        textNew = text.GetComponent<Text>();

        
        //世界坐标 position
        //transform.position = new Vector3(0,0,0);
        //translate表示在某一个轴上移动相应的长度


    }
    private Text textNew;
    private int i = 0;
    private Vector3 vector;
    // Update is called once per frame
    void Update() //一帧一帧去更新 一秒会执行很多帧 
    {
        //在x轴方向一帧一帧移动一个单位,不断的移动
        //transform.Translate(1,0,0);


        //每秒移动2m
        //获取上一帧开始的时间到下一帧结束的时间,简称一帧
        //Time.deltaTime
        //Debug.Log($"当前是第{i}帧,上一帧时间为{Time.deltaTime}");
        // 1/Time.deltaTime == 表示一秒可以有多少帧
        // 2/(1/s)==2*s 表示每帧移动的米数
        //时间帧数很快,每一帧的时间都是不一样,直接使用会直接影响我们移动的速度-太快



        //键盘按键监听
        //anyKey表示监听按下任意键 --当前是否有任何键或鼠标按钮处于按下状态
        //键盘按下的前提--必须是鼠标必须在游戏里面
        /*if (Input.anyKey)
        {
            Debug.Log("您下了键盘任意键");
        }*/
        //第一种方式:实现物体的上下左右移动
        /*if (Input.GetKey(KeyCode.W))
        {
            //i++;
            transform.Translate(0, 0, 10 * Time.deltaTime);
            textNew.text = "按下W键";
        }else if (Input.GetKey(KeyCode.S))
        {
            transform.Translate(0, 0, -10 * Time.deltaTime);
            textNew.text = "按下S键";
        }
        else if (Input.GetKey(KeyCode.A))
        {
            transform.Translate(-10 * Time.deltaTime, 0, 0);
            textNew.text = "按下A键";
        }
        else if (Input.GetKey(KeyCode.D))
        {
            transform.Translate(10 * Time.deltaTime, 0, 0);
            textNew.text = "按下D键";
        }*/


        //第二种方式:虚拟轴--适配不同的仪器 我现在交互的硬件是硬盘 如果是手机那就是陀螺仪
        //如果是vr设备的话对于不同的设备可能需要判断不同的方式判断
        //轴 -1 0 1起始状态是0,如果我按下了右键,从0变到-1,
        x = Input.GetAxis("Horizontal");
        z = Input.GetAxis("Vertical");
        Debug.Log($"{x},{z}");

        //判断  拿到一个变化后的向量
        vector = new Vector3(x,0,z); //zero = (0,0,0)
        if (vector!=Vector3.zero) //不等于0说明按下了按键
        {
            //改变位置 --将物体朝向vector的方向就可以了 
            //transform.rotation --蜡烛的方向 
            transform.rotation = Quaternion.LookRotation(vector);
            //移动操作 --朝着这个方向并且朝着这个方向同步移动
            transform.Translate(Vector3.forward*2*Time.deltaTime);
        }
    }
}

完整效果如下:

动画.gif