2017-09-02 11 views
2

我在Unity中獲得了一個「立方體」。這個立方體有一個觸發器,當進入它時,物體被抓到空中。這是一個電梯,你可以在這裏看到一個例子。距離斯派羅2在Unity中構建一個可旋轉升降機

https://youtu.be/f8wWMa4N5mE?t=643

我使用的代碼是非常小的取小景現在

private float liftSpeed = 10; // the speed, the object is flying up 

private void OnTriggerStay(Collider col) 
{ 
    Rigidbody objectRigid = col.gameObject.GetComponent<Rigidbody>(); // get the rigidbody from the object in the trigger 

    if (objectRigid != null) // does it have a rigidbody? 
     objectRigid.velocity = new Vector3(objectRigid.velocity.x, liftSpeed, objectRigid.velocity.z); // make it fly in the air 
} 

所以我有一個電梯,這完全正常工作。但是當我旋轉電梯時,我希望它能夠正常工作。

一些例子(我gamne是3D)

lift rotated by 45 degrees


lift rotated by 90 degrees

那麼,如何才能讓我的升降工作 「轉」?

回答

1

您可以使用變形RotateAround方法進行旋轉,就像在視頻剪輯中一樣。

Transform t = col.gameObject.GetComponent<Transform>(); 
transform.RotateAround(Vector3.zero, Vector3.up, 20 * Time.deltaTime); 

給定的snipet讓對象圍繞它指向的軸旋轉。

+0

對不起,我不想旋轉播放器,我想讓播放器沿着電梯移動,即旋轉了X度 – Question3r

2

您可以使用transform.up來獲取升降機的向上方向,然後乘以升降機速度。

objectRigid.velocity = transform.up * liftSpeed; 

transform.up根據物體的旋轉方式發生變化,所以如果您的升降物向左旋轉,那麼升降物將物品移到左側。

+0

對不起,我用這段代碼和玩家仍然被推到空中..?我認爲你的代碼是正確的,但玩家仍然在Y – Question3r

+0

我在X上將電梯旋轉了55度進行測試 – Question3r

+0

您是否正在使用小寫transform.up?腳本是否附在電梯上? –

0
  1. 使電梯的玩家孩子OnTriggerEnter。
  2. 移動升降機
  3. 您可以使用RotateAround功能旋轉升降臺。玩家還應該隨同升降機一起旋轉,因爲它現在是升降機的小孩。
  4. 化妝球員的母公司爲空時,它使用OnTriggerExit
0

這是我解決問題的辦法是走出電梯觸發的。

電梯和EndPoint將爲空GameObjects。如果你想讓電梯有一個平臺或一個基地,你可以添加一個GameObject作爲你喜歡的形狀的電梯的孩子。

您需要將碰撞器連接到升降機並將其設置爲觸發器。

然後添加下面的腳本來提升空遊戲對象

using System.Collections; 
using System.Collections.Generic; 
using UnityEngine; 

public class MoveLift : MonoBehaviour { 

    public Transform end; 

    float speed = 4f; 

    bool liftActivated = false; 

    // Use this for initialization 
    void Start() { 

    } 

    // Update is called once per frame 
    void Update() { 
     if(liftActivated) 
     { 
      float step = speed * Time.deltaTime; 
      //To move up the lift 
      transform.position = Vector3.MoveTowards(transform.position, end.position, step); 
      //To spin the lift 
      transform.RotateAround(Vector3.up, 2 * Time.deltaTime); 

      //To stop spining the lift when it reaches the end of the path 
      if(transform.position.Equals(end.position)) 
       liftActivated = false; 
     } 
    } 

    void OnTriggerEnter(Collider other){ 
     liftActivated = true; 
     other.gameObject.transform.parent = this.transform; 
     other.gameObject.GetComponent<Rigidbody>().isKinematic=true; 
    } 
} 

那麼你應該決定是否一旦電梯到達它的目的地是誰擁有遷出平臺的玩家,或者如果你unparent它讓它掉下來,因爲行程結束