【发布时间】:2022-04-17 00:21:38
【问题描述】:
由于某种原因,弹丸会被发射,但仅在敌人与玩家接触时才会发射,并且由于某种原因非常缓慢。 下面是我的代码。
(我的弹丸上有一个单独的脚本,但只处理对玩家的伤害)
public class flyingEnemy : MonoBehaviour {
public int maxHealth = 40;
Rigidbody2D rb2d;
public float speed;
public float attackRange;
private float lastAttackTime;
public float attackDelay;
public Transform target;
public float chaseRange;
public GameObject projectile;
public float bulletForce;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
float distanceToTarget = Vector3.Distance(transform.position, target.position);
if(distanceToTarget < chaseRange)
{
//start chasing player
Vector3 targetDir = target.position - transform.position;
float angle = Mathf.Atan2(targetDir.y, targetDir.x) * Mathf.Rad2Deg - 90f;
Quaternion q = Quaternion.AngleAxis(angle, Vector3.forward);
transform.rotation = Quaternion.RotateTowards(transform.rotation, q, 180);
transform.Translate(Vector3.up * Time.deltaTime * speed);
}
if(distanceToTarget < attackRange)
{
//check to see if its time to attack again
if (Time.time > lastAttackTime + attackDelay)
{
//do we have lineofsight?
RaycastHit2D Hit = Physics2D.Raycast(transform.position, transform.up,attackRange);
//what did the raycast hit?
if (Hit.transform == target)
{
GameObject newBullet = Instantiate(projectile, transform.position, transform.rotation);
newBullet.GetComponent<Rigidbody2D>().AddRelativeForce(new Vector2(0f, bulletForce));
lastAttackTime = Time.time;
}
}
}
}
【问题讨论】:
-
好吧,弹丸似乎只在玩家与敌人接触时才会发射,我希望它们可以发射任何距离,但它们也很慢。