2017-09-29 8 views
0

ピンボールテーブルのプランジャを作ろうとしています。基本的には、剛体とスプリングジョイントが取り付けられた立方体です。特定のキーが押されると、私は、スプリングのconnectedAnchorにz値を追加してキューブを移動しようとしています。そして、キーが押されなくなったら、connectedAnchorは元の位置に戻ります。相対的に連結されたアンカー付きのスプリングジョイント

問題はconnectedAnchor操作がワールドスペースで発生し、テーブルが回転しているためにz軸に沿ってキューブを移動することが正しくないことです。基本的に私が探しているのは、連結されたアンカーを実行する方法ですが、ワールド座標軸ではなくキューブの変換にローカルな軸を使用することです。

元の接続されたアンカーを取得するには、「自動設定」をチェックしてから、操作を行う前にチェックを外してください。 Joint.connectedAnchorのユニティドキュメントは、これはうまくいくと言いますが、そうではありません。

Here's my script: 

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

public class PlungerController : MonoBehaviour { 

    public float movement_increment_z; 

    public float max_movement_z; 

    private SpringJoint spring; 
    private Vector3 orig_anchor; 

    private void Start() { 
     spring = GetComponent<SpringJoint>(); 
     if (!spring) { throw new System.Exception("spring joint is needed"); }; 
     orig_anchor = spring.connectedAnchor; 
    } 

    public void processPlungerInput (bool isKeyPressed) { 
     Debug.Log(orig_anchor); 
     if (isKeyPressed) { 
      if (spring.connectedAnchor.z < max_movement_z) { 
       spring.connectedAnchor += new Vector3(0,0,movement_increment_z); 
      } else { 
       spring.connectedAnchor = orig_anchor; 
      } 
     } 
    } 

} 

剛体は、z軸の移動以外のすべてに拘束されます。

答えて

0

私はやや異なったアプローチをとった。バネの接続されたアンカーを変更するのではなく、私はそれを一定に保ち、接続された本体を静的に配置された原点変換に設定しました。

キーを押すと、一時的にスプリングを0に設定してから、プランジャオブジェクトの位置を変更します。キーが押されていないときは、スプリングを高い値に設定して、アンカーポイントにスナップバックします。

リジッドボディインスペクタのオプション(ワールドスペース軸上の位置のみをロックする)を使用する代わりに、回転とx/yの位置を各フレームの元の値に設定するスクリプトを使用しました。

スクリプトは次のようになります。

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

public class PlungerController : MonoBehaviour { 

    public float movement_increment_z; 

    public float max_movement_z; 
    public float spring_power; 

    private SpringJoint spring; 
    private Vector3 orig_anchor; 
    private Quaternion orig_rotation; 
    private float orig_pos_x, orig_pos_y; 

    private void Start() { 
     spring = GetComponent<SpringJoint>(); 
     if (!spring) { throw new System.Exception("spring joint is needed"); }; 
     orig_anchor = spring.connectedAnchor; 
     orig_rotation = transform.localRotation; 
     orig_pos_y = transform.localPosition.y; 
     orig_pos_x = transform.localPosition.x; 
    } 

    public void processPlungerInput (bool isKeyPressed) { 
     if (isKeyPressed) { 
      spring.spring = 0; 
      if (transform.localPosition.z < max_movement_z) { 
       transform.localPosition += new Vector3(0,0,movement_increment_z); 
      } 
     } else { 
      spring.spring = spring_power; 
     } 
    } 

    // preserve only z axis movement and no rotation at all. 
    private void FixedUpdate() { 
     transform.localRotation = orig_rotation; 
     transform.localPosition = new Vector3(orig_pos_x, orig_pos_y, transform.localPosition.z); 
    } 

} 
関連する問題