在 Unity UI 中加入一個 Text 元件,命名為 GScensor,並在其中加入以下 GScensor.cs 程式元件.
程式中會置入 Gyroscope & Acceleration (陀螺儀和重力加速器) 數據偵測.
GScensor.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Gscensor : MonoBehaviour
{
//public Ball ball;
private bool isHasGyro = false;
private Text infoMsg;
// Use this for initialization
void Start () {
// 自動抓取 Text 元件(看 C# 程式掛在哪個 Component 下,就抓哪個)
infoMsg = GetComponent<Text>();
if(SystemInfo.supportsGyroscope){
Input.gyro.enabled = true;
isHasGyro = true;
infoMsg.text = "Use Gyroscope";
}
else{
infoMsg.text = "Use GSensor";
}
}
// Update is called once per frame
void Update () {
float x1;
float y1;
float z1;
float x2;
float y2;
float z2;
x1=y1=z1=x2=y2=z2=0f;
//Vector3 force;
if(isHasGyro){ // 如果有「陀螺儀 (Gyroscope)」
x1 = Input.gyro.attitude.x*10.0F;
y1 = Input.gyro.attitude.y*10.0F;
z1 = Input.gyro.attitude.z*10.0F;
x2 = Input.acceleration.x*10.0F;
y2 = Input.acceleration.y*10.0F;
z2 = Input.acceleration.z*10.0F;
//infoMsg.text = "Use Gyroscope : " + x1 + " , " + y1 + " , " + z1;
//force = new Vector3(-x * 10.0F, 0.0F, -y * 10.0F);
}
else{ // 不然就只使用「重力感測器 G-Sensor」
x2 = Input.acceleration.x*10.0F;
y2 = Input.acceleration.y*10.0F;
z2 = Input.acceleration.z*10.0F;
//infoMsg.text = "Use Acceleration : " + x2 + " , " + y2 + " , " + z2;
//force = new Vector3(x*10.0F , 0.0F, y*10.0F);
}
infoMsg.text = "Use Gyroscope : " + Mathf.Round(x1) + " , " + Mathf.Round(y1) + " , " + Mathf.Round(z1);
infoMsg.text +="\n"; // 文字折行
infoMsg.text += "Use Acceleration : " + Mathf.Round(x2) + " , " + Mathf.Round(y2) + " , " + Mathf.Round(z2);
//ball.forward(force);
}
}
沒有留言:
張貼留言