试图向游戏对象发射射弹,不动!=

时间:2015-03-28 18:01:24

标签: c# unity3d unity3d-2dtools

我正在进行2D塔防游戏,并且希望我的塔能够在小兵身上发射预制件。然而,它目前只生成我想要的预制件,但不会移动它。

我的两个脚本:

public class Attacker : MonoBehaviour {

// Public variables
public GameObject ammoPrefab;
public float reloadTime;
public float projectileSpeed;

// Private variables
private Transform target;


// Use this for initialization
void Start () {
}

// Update is called once per frame
void Update () {

}
void OnTriggerEnter(Collider co){
    if (co.gameObject.tag == "Enemy" || co.gameObject.tag == "BlockTower") { 
        Debug.Log("Enemy tag detected");

        if(this.gameObject.tag == "Enemy" && co.gameObject.tag != "Enemy"){
            Debug.Log("This is an Enemy");
            // Insert for Enemey to attack Block Towers.
        }
        if(this.gameObject.tag == "Tower" && co.gameObject.tag != "BlockTower"){
            Debug.Log("This is a Tower");
            Tower Tower = GetComponent<Tower>();
            Tower.CalculateCombatTime(reloadTime, projectileSpeed);
            Transform SendThis = co.transform;
            Tower.SetTarget(SendThis);
        }
    }
}

}

public class Tower : MonoBehaviour {
private Transform target;
private float fireSpeed;
private double nextFireTime;
private GameObject bullet;
private Attacker source;

// Use this for initialization
public virtual void Start () {
    source = this.GetComponent<Attacker> ();
}

// Update is called once per frame
public virtual void Update () {

    if (target) {
        Debug.Log("I have a target");
        //if(nextFireTime <= Time.deltaTime)
        FireProjectile ();
    }
}
public void CalculateCombatTime(float time, float speed){
    Debug.Log("Calculate Combat Speed");
    nextFireTime = Time.time + (time * .5);
    fireSpeed = speed;
}
public void SetTarget(Transform position){
    Debug.Log("Set Target");
    target = position;
}
public void FireProjectile(){
    Debug.Log("Shoot Projectile");
    bullet = (GameObject)Instantiate (source.ammoPrefab, transform.position, source.ammoPrefab.transform.rotation);
    float speed = fireSpeed * Time.deltaTime;
    bullet.transform.position = Vector3.MoveTowards (bullet.transform.position, target.position, speed);
}

}

基本攻击者检测到与其发生碰撞的对象,然后如果其标记为塔,它将向塔发送信息。我的调试显示每个函数都有效,即使出现"Debug.Log("Shoot Projectile");"

然而它不会向我的目标移动,所以我猜"bullet.transform.position = Vector3.MoveTowards (bullet.transform.position, target.position, step);"永远不会被执行?

2 个答案:

答案 0 :(得分:0)

您必须更新项目符号的位置。只有在创建子弹时才会移动。

尝试制作项目符号列表并使用更新功能更改位置。

答案 1 :(得分:0)

Vector3.MoveTowards只移动对象一次,只是在调用FireProjectile时立即移位。

您需要使用Update()函数创建某种类型的弹丸脚本,以使其随时间移动。

以下是一个例子:

public class Projectile : MonoBehaviour
{
    public Vector3 TargetPosition;

    void Update()
    {
        transform.position = Vector3.MoveTowards(transform.position, TargetPosition, speed * Time.DeltaTime);
    }
}

然后在你的子弹实例化之后,设置目标:

bullet.GetComponent<Projectile>().TargetPosition = target.position;

希望它有所帮助。