簡體   English   中英

將子彈射向最后玩家位置的方向

[英]Shoot bullet to direction of last player position

我正在嘗試為正在將激光子彈射擊到玩家最后位置的無人機編碼。 子彈也應該旋轉到玩家位置。

我有以下腳本,但是由於某種原因它無法拍攝。

using System.Collections.Generic;
using UnityEngine;

public class DroneShoot: MonoBehaviour
{

    public Transform bulletspawn;
    public Rigidbody2D bulletPrefab;
    public float bulletSpeed = 750;
    public float bulletDelay;

    private Transform player;
    private Rigidbody2D clone;

    // Use this for initialization
    void Start()
    {
        player = GameObject.FindGameObjectWithTag("spieler").GetComponent<Transform>();
    StartCoroutine(Attack());
    }

    IEnumerator Attack()
    {
        yield return new WaitForSeconds(bulletDelay);
        if (Vector3.Distance(player.transform.position, bulletspawn.transform.position) < 20)
        {
            Quaternion rotation = Quaternion.LookRotation(player.transform.position, bulletspawn.transform.position);
            bulletspawn.rotation = rotation;
            clone = Instantiate(bulletPrefab, bulletspawn.position, bulletspawn.rotation);

            clone.AddForce(bulletspawn.transform.right * bulletSpeed);
            StartCoroutine(Attack());
        }
    }
}

看起來它只會在第一次啟動時嘗試再次啟動,因為StartCoroutine在距離檢查中。

我認為它應該永遠嘗試射擊。

IEnumerator Attack()
{
    while(true){
        yield return new WaitForSeconds(shootDelay);
        if (Vector3.Distance(player.transform.position, bulletspawn.transform.position) < 20)
        {
            Quaternion rotation = Quaternion.LookRotation(player.transform.position);
            bulletspawn.rotation = rotation;
            clone = Instantiate(bulletPrefab, bulletspawn.position, bulletspawn.rotation);

            clone.AddForce(bulletspawn.transform.right * bulletSpeed);
        }
    }
}

我有解決辦法。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DroneShoot: MonoBehaviour
{

public Transform bulletspawn;
public Rigidbody2D bulletPrefab;
public float bulletSpeed = 750;
public float bulletDelay;

private Transform player;
private Rigidbody2D clone;

// Use this for initialization
void Start()
{
    player = GameObject.FindGameObjectWithTag("spieler").GetComponent<Transform>();
    StartCoroutine(Attack());
}

IEnumerator Attack()
{
    yield return new WaitForSeconds(bulletDelay);
    if (Vector3.Distance(player.transform.position, bulletspawn.transform.position) < 20)
    {

        Vector3 difference = player.position - bulletspawn.position;
        float rotationZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
        bulletspawn.rotation = Quaternion.Euler(0.0f, 0.0f, rotationZ);

        clone = Instantiate(bulletPrefab, bulletspawn.position, bulletspawn.rotation);

        clone.AddForce(bulletspawn.transform.right * bulletSpeed);
        StartCoroutine(Attack());
    }
}
}

暫無
暫無

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

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