unity加速传感器的应用
生活随笔
收集整理的這篇文章主要介紹了
unity加速传感器的应用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1、加速傳感器 ??? 在塞車類游戲中,通過移動設備的左右傾斜來模擬游戲中的方向盤,這就用到了加速傳感器。可以開發跑酷類游戲。
2、基礎知識:
線性加速度三維向量x,y,z分別標識手機屏幕豎直、水平、垂直方向。通過手機重力傳感器就能獲取手機移動或旋轉過程中的3個分量,使用時在代碼中調用Input.acceleration方法即可。
3、案例介紹: 傾斜手機,移動小球,當小球到達光圈位置時,傳送到另一個光圈的位置(類似LOL里的傳送),如下圖1,2所示。
圖1
圖2
開發流程,
1、搭建場景:BlueClinderFX為粒子特效,其他都是用plane,cube,sphere進行搭建。如圖3所示。
圖3
2、場景創建完成后,利用加速傳感器,操控手機控制小球的移動。
UpdateInput()函數作用是通過鼠標空盒子小球移動,便于在電腦上操控小球。
flag標志位,相當于一個開關,控制特效的顯示和隱藏。
Invoke 為一定時間后執行某個方法。
dir.x = Input.acceleration.x; 三維向量的x分量為加速度傳感器的x分量
dir.z = Input.acceleration.y; 三維向量的z分量為加速度傳感器的y分量
完整代碼如下:
using UnityEngine; using System.Collections; public class Control : MonoBehaviour{public Transform destroy; //聲明掛載BlueClinderFX游戲對象的變量public Transform flash; //聲明掛載BlueClinderFX(1)游戲對象的變量public Transform sphere; //聲明場景中小球的游戲變量Vector3 dir = Vector3.zero; //聲明一個三維向量的變量private float distance; //定義距離變量private bool flag=false; //聲明一個用來判斷小球是否消失的標志位private float mindistance = 2.0f; //定義小球和BlueClinderFX游戲對象的最小距離變量private Vector3 currentPos;private float speed = 5.0f;void Update(){UpdateInput();dir.x = Input.acceleration.x; //三維向量的x分量為加速度傳感器的x分量dir.z = Input.acceleration.y; //三維向量的z分量為加速度傳感器的y分量this.transform.GetComponent<Rigidbody>().AddForce(dir*5);//為小球添加力的效果distance = Vector3.Distance(sphere.position, destroy.position);//獲取當前小球和BlueClinderFX的距離if(distance <= mindistance){sphere.position = destroy.position;//重置小球的當前位置Invoke("spheredestroy", 0.1f); //在0.1秒后調用spheredestroy方法flag = !flag; //標志位置反}if(flag){//destroy.gameObject.SetActive(true);//BlueClinderFXsphere.position = flash.position;//重置小球的當前位置flash.gameObject.SetActive(true);//將BlueClinderFX(1)游戲對象的active置為trueInvoke("sphereflash", 1.0f);//在1秒后調用sphereflash方法Invoke("flashreset", 10.0f);//在1秒后調用flashreset方法flag = !flag;//標志位置反}}void spheredestroy(){sphere.gameObject.SetActive(false);//將小球的active置為false(即為不可見)}void sphereflash(){sphere.gameObject.SetActive(true);//將小球的active置為true}void flashreset(){flash.gameObject.SetActive(false);//將BlueClinderFX(1)對象的active置為false}void UpdateInput(){if (Input.GetMouseButton(0)){Vector3 ms = Input.mousePosition;// ms = Camera.main.ScreenToWorldPoint(ms);Ray ray = Camera.main.ScreenPointToRay(ms);RaycastHit hit;if (Physics.Raycast(ray, out hit)){currentPos = hit.point;}Vector3 pos = Vector3.MoveTowards(this.transform.position, currentPos, speed * Time.deltaTime);this.transform.position = pos;}} }總結
以上是生活随笔為你收集整理的unity加速传感器的应用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: fastjson 1.2.24 反序列化
- 下一篇: bat 打开 任务管理器