[英]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.