将子弹射向最后玩家位置的方向

时间:2018-12-28 15:01:08

标签: c# unity3d

我正在尝试为正在将激光子弹射击到玩家最后位置的无人机编码。子弹也应该旋转到玩家的位置。

我有以下脚本,但由于某些原因无法拍摄。

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());
        }
    }
}

2 个答案:

答案 0 :(得分:0)

由于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);
        }
    }
}

答案 1 :(得分:0)

我有解决办法。

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());
    }
}
}