2017-12-20 11 views
0

私は現在、スクリーン上の任意のx位置から文字が画面の一番下の点に向かって動いているUnityでゲームをしています。彼らは一定のスピードを保たなければならない(そして、後で特定のパターンで動くことができる)ので、私はこれにVector3.Lerpを使用することはできません。Unityで数学を使ってスプライトを動かす

代わりに、私は単純な数学を使って試しました。 StaticInfo.instance.GetPlayerPosition()が目標位置です。コードはキャラクターのFixedUpdate()で発生します。

float aVal = (myTransform.localPosition.y - StaticInfo.instance.GetPlayerPosition().y)/
      (myTransform.localPosition.x - StaticInfo.instance.GetPlayerPosition().x); 
float degrees = Mathf.Atan(aVal) * Mathf.Rad2Deg; 
Vector3 newPos = new Vector3(myTransform.localPosition.x - (distance * speed * Mathf.Cos(degrees)), 
          myTransform.localPosition.y - (distance * speed * Mathf.Sin(degrees)), 
          1); 
myTransform.localPosition = newPos; 

私の問題は、これらの文字が作成された(プリファブからインスタンス化された)ときに、希望の方向に移動する前に小さな180度ループを作成することです。その後、彼らは望みどおりに動きます。

数値計算を使用していますか?それがそうであれば、なぜ初期化されたときにそれはファンキーなドリフトをしますか?

+0

てみてくださいAtan2(y、x)を使用して –

答えて

0

これはあなたが達成しようとしているものに、より簡単な解決策になることがあります。あなたはあなたが行うことができ、移動の方向にポイントにオブジェクトをしたい場合は

Vector3 moveDirection = (StaticInfo.instance.GetPlayerPosition() - myTransform.localPosition).normalized; 

    Vector3 newPos = myTransform.localPosition + moveDirection * distance * speed; 

    myTransform.localPosition = newPos; 

myTransform.rotation = Quaternion.Euler(0, 0, Mathf.atan2(moveDirection.y, moveDirection.x)*Mathf.Rad2Deg - 90); // may not need to offset by 90 degrees here; 
+1

'moveDirection'を正規化する必要があります。 – meowgoesthedog

+0

moveDirectionに常に向くように、順方向変換をする必要があります。彼の問題は何だったのか。それでも、これは移動部分にとってより簡単です。 –

+0

チャームのように働いた。ありがとう – JaisBC

関連する問題