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

 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放入 调用

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值