2017年3月29日 星期三

Week6 JimC

一.操控提起物件

利用手桿拿起地上的物件









程式碼

using System.Collections;
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// Throw object.
/// Component SteamVR_TrackedObject  元件
/// RequireComponent ---> 控制器 所需 之 元件
/// typeof ---> 型態為一個 SteamVR_TrackedObject
/// </summary>
[RequireComponent(typeof(SteamVR_TrackedObject))]

public class ThrowObject : MonoBehaviour
{

SteamVR_TrackedObject trackedObj;//C# 中的參考變數
SteamVR_Controller.Device device;
public float speedUp = 3.0f;
public GameObject Ball;

/// <summary>
/// Awake this instance.
/// Unity 生命週期圈(LifeCycle)中的Awake()區塊
/// 根據 Execution Order FlowChart事件執行流程圖
/// Unity 初始期(Initialization)共分為三小階段
/// 1.Awake()--->2.OnEnable()--->3.Start()
/// Awake()只會做一次!!!
/// OnEnable() 會持續和 OnDisable(某物件關閉) 做loop狀態切換
/// Start()
/// 抓 tracking object
/// 若程式很常寫Inable  和 Disable
/// 那就要寫在Start()
/// </summary>
void Awake()
{
trackedObj= GetComponent<SteamVR_TrackedObject>();
// 取得TrackedObject中的各個元素
}
/// <summary>
/// Fixeds the update.
/// FixedUpdate() 執行區塊較Update()區塊還要前
/// 主要是做  物理方面操作(Physics)
/// Update() 通常是做  遊戲Logic
/// </summary>
void FixedUpdate()
{
device = SteamVR_Controller.Input ((int)trackedObj.index);
if (device.GetTouchDown (SteamVR_Controller.ButtonMask.Grip))
{
GameObject ball = GameObject.Instantiate (Ball);
ball.transform.position = new Vector3 (0f, 1f, -0.5f);
}
}

void OnTriggerStay(Collider col)
{
Debug.Log ("碰到!!!!");
if (device.GetTouchDown (SteamVR_Controller.ButtonMask.Trigger))
{
Debug.Log ("抓起!!!");
col.attachedRigidbody.isKinematic = true;
col.gameObject.transform.SetParent (gameObject.transform);//設定 Controller 為父親
}
if (device.GetTouchUp (SteamVR_Controller.ButtonMask.Trigger))
{
Debug.Log ("放開!!!");
col.gameObject.transform.SetParent (null);
col.attachedRigidbody.isKinematic = false;
GameObject.Destroy (col.gameObject, 3f);
tossObject (col.attachedRigidbody);
}
}
void tossObject(Rigidbody rigidBody)
{
rigidBody.velocity = device.velocity * speedUp;
rigidBody.angularVelocity=device.angularVelocity;
}

}

研究教室體驗VR

探討作品主題與目標

沒有留言:

張貼留言