矢印キーを使用して1x1パイプの周りで立方体を回転させたい。(左右)。
問題は、トランスフォームの位置と場所を直接設定する組み込み関数を使用できないことです。(transform.lookAt、transform.Rotate、transform.RotateAroundなど)。回転させたい変換の値を変更する前に、複数のものの回転のオイラーと位置のベクトル値が必要なためです。
私はさまざまなテクニックを試しましたが、今のところ運がありません。
回転にsin-cosを使用してみましたが、回転と位置の両方で機能させる方法がわかりませんでした。
_timer += Time.deltaTime * _larvaSpeed;
float x = -Mathf.Cos(_timer) * distanceBetweenCenter;
float y = Mathf.Sin(_timer) * distanceBetweenCenter;
これが私が達成したいことです。右または左を押して、パイプの周りでオブジェクトを移動および回転させます。
私が望む結果。(右矢印キーを少し押した場合)。
助けていただければ幸いです。ありがとうございました!
これが円数学を使用した解決策であり、使用しないことを強くお勧めします。@ FaTaLLがコメントで尋ねているように、円方程式を使用して円運動を理解するだけです。
円方程式...(x1-x2)^ 2 +(y1-y2)^ 2 = r ^ 2
x1、y1は立方体の位置です
x2、y2はパイプの位置です
rは立方体とパイプの間の距離です。
using UnityEngine;
public class Rotating : MonoBehaviour
{
public GameObject pipe;
public float Delta;
Vector3 nextpos;
bool compareY;
bool next;
int switchx;
float storeVarAxis;
float x, y, r;
private void Start()
{
next = true;
switchx = 1;
compareY = true;
x = transform.position.x - pipe.transform.position.x;
y = transform.position.y - pipe.transform.position.y;
storeVarAxis = y;
r = Mathf.Sqrt(x * x + y * y);
}
private void Update()
{
if (next)
{
if (compareY == true)
{
y -= Delta * Time.deltaTime;
if (y <= -storeVarAxis)
{
y = -storeVarAxis;
compareY = false;
switchx = -1;
}
}
else
{
y += Delta * Time.deltaTime;
if (y >= storeVarAxis)
{
y = storeVarAxis;
compareY = true;
switchx = 1;
}
}
float v = r * r - y * y;
x = Mathf.Sqrt(Mathf.Abs(v));
nextpos = new Vector3(pipe.transform.position.x + x * switchx, pipe.transform.position.y + y, transform.position.z);
next = false;
}
transform.position = Vector3.MoveTowards(transform.position, nextpos, 1f * Time.deltaTime);
if(Vector3.Distance(transform.position, nextpos) < .05) transform.position = nextpos;
if (transform.position.x.Equals(nextpos.x) && transform.position.y.Equals(nextpos.y)) next = true;
}
}
まあ、推奨される方法は、この単純なスクリプトを使用することです
using UnityEngine;
public class Rotating : MonoBehaviour
{
public float speed;
public GameObject pipe;
float r, angle;
Vector3 startpos;
private void Start()
{
r = Mathf.Abs(transform.position.y - pipe.transform.position.y);
angle = 0;
transform.position = pipe.transform.position;
startpos = transform.position;
}
void Update()
{
angle = angle + speed * Time.deltaTime;
transform.rotation = Quaternion.EulerAngles(0,0, angle);
transform.position = startpos + (transform.rotation * new Vector3(r, 0, 0));
}
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加