0

メイン カメラが向いている方向に対してワールド空間でターゲット オブジェクトを移動する必要がありますが、x&z 軸上でのみ、y 軸上のプレーヤーに対してのみ移動する必要があります。

どんなガイダンスも大歓迎です。

public class test : MonoBehaviour {

public string raise = "Raise";
public string lower = "Lower";
public string left = "Left";
public string right = "Right";
public string closer = "Closer";
public string further = "Further";

public GameObject target;


private float xPos;
private float yPos;
private float zPos;


// Use this for initialization
void Start () {


    xPos = target.transform.position.x;
    yPos = target.transform.position.y;
    zPos = target.transform.position.z;

}

void FixedUpdate () {

    Vector3 currPos = target.transform.position;
    Vector3 nextPos = new Vector3 (xPos, yPos, zPos);

    target.GetComponent < Rigidbody > ().velocity = (nextPos - currPos) * 10;

    if (Input.GetButton (raise)) {
        print ("Moving Up");
        yPos = yPos + 0.05f;
    }
    if (Input.GetButton (lower)) {
        print ("Moving Down");
        yPos = yPos - 0.05f;
    }
    if (Input.GetButton (left)) {
        print ("Moving Left");
        xPos = xPos - 0.05f;
    }
    if (Input.GetButton (right)) {
        print ("Moving Right");
        xPos = xPos + 0.05f;
    }
    if (Input.GetButton (closer)) {
        print ("Moving Closer");
        zPos = zPos - 0.05f;
    }
    if (Input.GetButton (further)) {
        print ("Moving Further");
        zPos = zPos + 0.05f;
    }
}
4

1 に答える 1

2

次のようにカメラの方向を取得できます。

var camDir = Camera.main.transform.forward;

x/y コンポーネントのみが必要なため、そのベクトルを再正規化します。

camDir.y = 0;
camDir.Normalized();

それが前方ベクトルです。これは事実上 2D ベクトルになっているため、カムの右側のベクトルを簡単に取得できます。

var camRight = new Vector3(camDir.z, 0f, -camDir.x);

プレーヤーの上方向が y 軸のすぐ上にあると仮定します。異なる場合は、そのベクトルにサブします。

var playerUp = Vector3.up;

今、あなたのサンプルでは手動で統合を行っており、それを剛体システムに渡して再度統合を行っています。自分の速度を直接計算してみましょう。

var newVel = Vector3.zero;
if (/*left*/) newVel -= camRight * 0.05;
if (/*right*/) newVel += camRight * 0.05;
if (/*closer*/) newVel -= camDir * 0.05;
if (/*farter*/) newVel += camDir * 0.05;
if (/*raise*/) newVel += playerUp * 0.05;
if (/*lower*/) newVel -= playerUp * 0.05;

より速くまたはよりゆっくり移動したい場合は、その 0.05 を変更します。ここでは、小さなデッドゾーンを設定したり、ボタンではなくアナログ入力から直接供給したりするなど、コントロールを本当に快適にするために多くのことを行うことができます。

最後に、それを剛体にコミットします。

target.GetComponent<Rigidbody>().velocity = newVel;
于 2015-04-29T17:36:06.977 に答える