簡體   English   中英

如何使子彈射向游戲對象

[英]How to get a projectile to shoot towards a gameobject

我目前正在研究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秒只拍攝一次,任何幫助都會很棒。

您已經很接近了,您需要更改以下行:

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

對此:

private const int SPAWN_DISTANCE = 5;

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

Quaternion.identity是指:

該四元數對應於“不旋轉”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM