2014-12-06 39 views
1

我目前正在使用TurretAi。我擁有它,以便當敵人在一定範圍內時,炮塔瞄準敵人,但是我無法讓炮塔向敵人發射炮彈。這是目前我所擁有的這種炮塔類。如何讓彈丸射向遊戲對象

using UnityEngine; 
using System.Collections; 

public class Defence : MonoBehaviour { 

    public float DistanceFromCastle,CoolDown; 
    public GameObject enemy; 
    public GameObject Bullet; 
    public int protectionRadius,bulletSpeed; 

    // Use this for initialization 
    void Start() 
    { 
     protectionRadius = 35; 
     bulletSpeed = 50; 
     CoolDown = 5; 

    } 

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

     enemy = GameObject.FindGameObjectWithTag("Enemy"); 

     if(enemy != null) 
     { 
      DistanceFromCastle = Vector3.Distance(GameObject.FindGameObjectWithTag("Enemy").transform.position,GameObject.FindGameObjectWithTag("Defence").transform.position); 
      //print (DistanceFromCastle); 
      if(DistanceFromCastle <= protectionRadius) 
      { 
       attackEnemy(); 
      } 

     } 
    } 
    void attackEnemy() 
    { 
     transform.LookAt(enemy.transform); 
     CoolDown -= Time.deltaTime; 
     if (CoolDown <= 0) 
     { 

      Debug.DrawLine(transform.position,enemy.transform.position,Color.red); 
      Instantiate(Bullet,Vector3.forward,Quaternion.identity); 

      print("attack Enemy"); 
      CoolDown = 5; 
     } 
    } 
} 

我也已經有一個冷卻變種,使其只能拍每5秒任何幫助將是真棒。

回答

1

你是相當接近,你需要改變這一行:

Instantiate(Bullet, Vector3.forward, Quaternion.identity); 

要這樣:

private const int SPAWN_DISTANCE = 5; 

Instantiate(Bullet, transform.position + SPAWN_DISTANCE * transform.forward, transform.rotation); 

Quaternion.identity是指:

這四元數對應於「不旋轉」。

+0

當我改變這一點,子彈不會從炮塔所在的直線上開火 – user2552211 2014-12-06 02:00:58

+0

你的炮塔有很多零件嗎?不要告訴我你旋轉頂部和腳本連接到基地。 – FunctionR 2014-12-06 02:03:03

+0

我只是把它附在一個立方體上,當它的射程在我想要射出的射彈上時,讓這個立方體看着它的對象 – user2552211 2014-12-06 02:04:56