完成後跟老師討論,發現按壓旋轉的方式非常不方便,於是更改為滑動方式並加入過關條件
1.更改程式碼如下
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
[RequireComponent(typeof(SteamVR_TrackedObject))]
public class ControllerTest : MonoBehaviour {
SteamVR_TrackedObject trackedObj;
SteamVR_Controller.Device device,deviceLeft,deviceRight;
public GameObject obj;
float a=0.0f,b=0.0f,c=0.0f;
Vector2 rotat=new Vector2(0.0f,0.0f);
public static bool over=false;
void Start () {
trackedObj=GetComponent<SteamVR_TrackedObject>();
a=obj.transform.rotation.x;
b=obj.transform.rotation.y;
c=obj.transform.rotation.z;
}
// Update is called once per frame
Vector2 tp2;
bool bTouched=false;
void Update () {
device = SteamVR_Controller.Input ((int)trackedObj.index);
var leftHand = SteamVR_Controller.GetDeviceIndex(SteamVR_Controller.DeviceRelation.Leftmost);
deviceLeft = SteamVR_Controller.Input (leftHand);
var rightHand = SteamVR_Controller.GetDeviceIndex(SteamVR_Controller.DeviceRelation.Rightmost);
deviceRight = SteamVR_Controller.Input (rightHand);
Vector2 tp=Vector2.zero,tp1=Vector2.zero;
if (device.GetTouch (SteamVR_Controller.ButtonMask.Touchpad)){
//由原先的GetPress更改為GetTouch
tp2 = tp1;//備份第一次碰到的位置
tp1 = device.GetAxis ();//備份完後再讀取Touchpad碰到的位置
if(bTouched){
rotat=tp1-tp2;
//print("tp1:"+tp1+"\n");
//print("tp2:"+tp2);
//print("diff:"+ (tp1-tp2));
///....
float angle=Vector2.Angle (new Vector2 (1, 0), rotat);
if (angle > 45 && angle < 135) {
if (rotat.y > 0){
a+=3.0f;
if(a>180.0f)
a%=180.0f;
}
else{
a-=3.0f;
if(a<-180.0f)
a%=180.0f;
}
}
else {
if (rotat.x>0){
b+=3.0f;
if(b>180.0f)
b%=180.0f;
}
else{
b-=3.0f;
if(b<-180.0f)
b%=180.0f;
}
}
}
bTouched=true;
}
else
bTouched=false;
obj.transform.rotation = Quaternion.Euler (new Vector3 (a, b, c));
if((a<=-5.0f && a>=-25.0f) && (b<=80.0f && b>=60.0f)){
//若物件達到指定角度
over=true;
SceneManager.LoadScene ("start_menu");
}
}
}
2.過關條件判斷
因為我們程式的寫法是一直累加或減角度,導致最後數值會大於或小於360度,所以在做條件判斷時需將數值除以180取餘數,以取得正確的數值
if (angle > 45 && angle < 135) {
if (rotat.y > 0){
a+=3.0f;
if(a>180.0f)
a%=180.0f;
}
else{
a-=3.0f;
if(a<-180.0f)
a%=180.0f;
}
}
else {
if (rotat.x>0){
b+=3.0f;
if(b>180.0f)
b%=180.0f;
}
else{
b-=3.0f;
if(b<-180.0f)
b%=180.0f;
}
}
沒有留言:
張貼留言