0

Unityでタワーディフェンスゲームを実装しようとしていますが、(作成者オブジェクトのスクリプトで)新しいインスタンス化されたオブジェクトに速度または力を割り当てる方法がわかりません。発射するはずのタワーがあります。コライダーをトリガーした敵への弾丸。これは塔の台本です:

function OnTriggerEnter(other:Collider){
if(other.name=="Enemy")
{
ShootBulletTo(other.transform);
}
}

function ShootBulletTo(target:Transform)
{//public var Bullet:Transform
var BulletClone = Instantiate(Bullet,transform.position, Quaternion.identity); // ok
BulletClone.AddForce(target.position); //does not compile since Transform.AddForce() does not exist.
}

Transform問題は、インスタンス化に変数を使用する必要があることだと思いますがGameObject、速度、力などの変数が必要です。では、どのようにして弾丸を初速度でインスタンス化できますか?手伝ってくれてありがとう。

4

1 に答える 1

2

変換ではなく力を変更するには、弾丸のクローンの Rigidbody コンポーネントにアクセスする必要があります。

コードは次のようになります。

function OnTriggerEnter(other:Collider)
{
    if(other.name=="Enemy")
    {
       ShootBulletTo(other.transform);
    }
}

function ShootBulletTo(target:Transform)
{
    var Bullet : Rigidbody;
    BulletClone = Instantiate(Bullet, transform.position, Quaternion.identity);

    BulletClone.AddForce(target.position); 
}

Unity スクリプト リファレンスhttp://docs.unity3d.com/Documentation/ScriptReference/Object.Instantiate.htmlにも良い例があり ます。

[編集] 敵の位置を力として追加したくないと確信しています。代わりに、敵の位置に向かう方向を追加する必要があります。2 つの位置を差し引いて、それらの間の方向ベクトルを取得するため、ShootBulletTo 関数は次のようになります。

function ShootBulletTo(target:Transform)
{
    // Calculate shoot direction
    var direction : Vector3;
    direction = (target.position - transform.position).normalized;

    // Instantiate the bullet
    var Bullet : Rigidbody;
    BulletClone = Instantiate(Bullet, transform.position, Quaternion.identity);

    // Add force to our bullet
    BulletClone.AddForce(direction); 
}
于 2012-12-31T12:22:31.590 に答える