[英]Trying to launch a projectile towards a gameobject, doesn't move!=
我正在制作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);
}
}
基本上,攻擊者會檢測與之碰撞的對象,然后,如果其標簽為Tower,它將信息發送給Tower。 我的調試顯示,每個函數都可以正常運行,甚至是"Debug.Log("Shoot Projectile");"
出現。
但是它並沒有移向我的目標,所以我猜"bullet.transform.position = Vector3.MoveTowards (bullet.transform.position, target.position, step);"
永遠不會被執行?
您必須更新項目符號的位置。 您僅在創建項目符號時移動。
嘗試列出項目符號列表,並使用更新功能更改位置。
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;
希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.