2017-10-10 80 views
1

重要提示:我知道我可以創建一個空的gameobject,將門作爲其子項並旋轉此軸心點。但我想通過代碼來完成。在Unity中設置旋轉門的樞軸點

所以我有一個可轉動的門在統一。我通過代碼創建一個樞軸點並嘗試旋轉它。門相對於其父母旋轉。

[SerializeField] 
private Vector3 targetRotation; // rotation angles 

[SerializeField] 
private float duration; // rotation speed 

[SerializeField] 
private bool closeAgain; // close the door again? 

[SerializeField] 
private float waitInterval; // close the door after x seconds 

private Vector3 defaultRotation; // store the rotation when starting the game 
private bool isActive = false; 

Transform doorPivot; // the pivot point to rotate around 

private void Start() 
{ 
    doorPivot = new GameObject().transform; // create pivot 
    transform.SetParent(doorPivot); // make the door being a child of the pivot 
    defaultRotation = doorPivot.eulerAngles; 
} 

private IEnumerator DoorRotation() 
{ 
    if (isActive) 
     yield break; 

    isActive = true; 

    yield return StartCoroutine(RotateDoor(doorPivot.eulerAngles + targetRotation)); // open the door 

    if (!closeAgain) 
     Destroy(this); // destroy the script if the door should stay open 

    yield return new WaitForSeconds(waitInterval); // wait before closing 

    yield return StartCoroutine(RotateDoor(defaultRotation)); // close the door 

    isActive = false; 
} 

private IEnumerator RotateDoor(Vector3 newRotation) // door rotation 
{ 
    float counter = 0; 
    Vector3 defaultAngles = doorPivot.eulerAngles; 
    while (counter < duration) 
    { 
     counter += Time.deltaTime; 
     doorPivot.eulerAngles = Vector3.Lerp(defaultAngles, newRotation, counter/duration); 
     yield return null; 
    } 
} 

public void Interact() // start the rotation 
{ 
    StartCoroutine(DoorRotation()); 
} 

當遊戲開始時,我調用該方法Interact()和門開始轉動。

樞軸點在(0,0,0)處創建,所以當將門放置在靠近此點時,旋轉會變得更好。如果門很遠,那麼旋轉是一個大圓圈。

所以我想到了將樞軸總是靠近門。但隨後門被移開,因爲它是樞軸的一個孩子。

我會創造一個新的領域的檢查

[SerializeField] 
Vector3 pivotPosition; // position of the pivotpoint 

和這個領域應該代表相對於門樞軸位置。

例如

enter image description here

用戶可以對自己的選擇放置支點,但放置時,門不應該獲得搬走。

有人可以幫我嗎?

+1

將支點移動到門上之後再將它作爲它的孩子。 –

+0

真實故事......好的,我會在這裏留下這篇文章 – peterHasemann

回答

0

@Chuck野人固定這個問題

[SerializeField] 
    private Vector3 pivotPosition; 

    private Vector3 defaultRotation; 

    Transform doorPivot; 

    private void Start() 
    { 
     doorPivot = new GameObject().transform; 
     doorPivot.position = pivotPosition; // place the pivot before parenting! 
     transform.SetParent(doorPivot); 
     defaultRotation = doorPivot.eulerAngles; 
    } 

開始養育之前剛剛成立的支點位置。