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

您必须访问子弹克隆的刚体组件才能更改力,而不是变换。

这是您的代码的外观:

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); 
}

在统一脚本参考 http://docs.unity3d.com/Documentation/ScriptReference/Object.Instantiate.html中也有一个很好的例子

[编辑] 我很确定,您不想将敌人的位置添加为力量,而是应该添加一个朝向敌人位置的方向。您减去两个位置以获得它们之间的方向向量,因此 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 回答