3.Unity中c#代码学习(按键+屏幕和三维坐标转换+组件的调用)

编程知识 行业动态 更新时间:2024-06-13 00:20:05

 if (Input.GetMouseButtonDown(0)) 0左键 1右键 2中键 判断鼠标按下         鼠标事件只触发一次

if (Input.GetMouseButtonUp(0))                                      判断鼠标抬起         事件探测

if (Input.GetMouseButton(0))                                           判断鼠标按住       事件是全局不被垄断

int width = Screen.width;
int high = Screen.height;
Debug.Log("屏幕:" + width + "," + high);                               屏幕像素大小

 if (Input.GetMouseButtonDown(0))
        {
           
Vector3 vector3Cube = Input.mousePosition;          获得鼠标在屏幕上的位置
            Debug.Log(vector3Cube);
        }

Vector3 pos = this.transform.position;
Vector3 screenPos = Camera.main.WorldToScreenPoint(pos);
Debug.Log("立方体屏幕坐标" + screenPos);                        将立方体三维坐标转换为屏幕坐标

if(screenPos.x<0||screenPos.x>Screen.width|| screenPos.y<0|| screenPos.y> Screen.height)
        {
            Debug.Log("正方块已出界");                                      判断物体是否出屏幕
        }

KeyCode - Unity 脚本 API

if (Input.GetKey(KeyCode.W)|| Input.GetKey(KeyCode.UpArrow))   判断按键是否按下   
        {
            this.transform.Translate(0, 0, speed * Time.deltaTime);
            //Debug.Log("按键W按下");
        }
        if (Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow))
        {
            this.transform.Translate(0, 0, -speed * Time.deltaTime);
        }
        if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
        {
            this.transform.Translate(-speed * Time.deltaTime, 0, 0);
        }
        if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
        {
            this.transform.Translate(speed * Time.deltaTime, 0, 0);
        }                                                               方向控制,是否按下 按下后转移方向

游戏启动时自动播放     

        通过GetComponent来调用<AudioSource>来进行赋值                <>指泛值

        AudioSource audio = this.GetComponent<AudioSource>();

UnityEngine.AudioSource - Unity 脚本 API
        audio.Play();

         GetComponent调用的是this有的组件

可以通过创建GameObject变量来访问其他结点

public GameObject bgmNode;              创建一个新的结点

AudioSource audio = bgmNode.GetComponent<AudioSource>();        把原有结点进行引用
audio.Play();                使用新结点

 public AudioSource bgm;通过创建AudioSource变量,直接将想要赋过来的bgm放入

public GameObject fanNode;                 创建一个新的结点

Revolve fan = fanNode.GetComponent<Revolve>();        把原有结点进行引用

 fan.rotateSpeed = 180;        使用新结点

public Revolve fan; 直接创建新的Revolve变量,直接将想要赋过来的fan放入 调用

更多推荐

3.Unity中c#代码学习(按键+屏幕和三维坐标转换+组件的调用)

本文发布于:2023-03-29 10:23:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/780b076d335b57d89b4a8abb596f7d0d.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:坐标   按键   组件   屏幕   代码

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!