2017年3月29日 星期三

虛擬實境 Week 06_周冠羽_立人老師影片教學_抓取物件_拉方塊重影繪圖_丟擲物品模擬之實踐

上半場:

研究室實際操作








下半場:

教室影片上課




一些程式重點

物件初始化之後第一調用的函數就是Awake
而Start是在物件初始化後,第一次Update之前調用的。


PS:在Start中進行初始化不是很安全,因為它可能被其他自定義的函數搶先。

PS:Awake無論物件是否是Active,
腳本是否enabled都會被調用,可以說是無論如何都會被調用的
而Start如果物件是被 SetAcive(false)或  enabled= false 則不會被調用的。












拿起來的

程式碼



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;
}

}













沒有留言:

張貼留言