c# - 敌人的弹丸没有朝正确的方向飞行?
问题描述
我无法让敌人的弹丸从敌人飞到玩家的位置。当我玩游戏时,敌人的子弹弹丸在屏幕上朝一个方向飞出,而不是朝玩家飞去。我认为问题可能在于我如何为弹丸预制件分配方向?任何建议将不胜感激。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyController : MonoBehaviour
{
public float speed;
public Rigidbody enemyRb;
[SerializeField] float rateOfFire;
private GameObject player;
public GameObject projectilePrefab;
float nextFireAllowed;
public bool canFire;
Transform enemyMuzzle;
void Awake()
{
enemyRb = GetComponent<Rigidbody>();
player = GameObject.Find("Player");
enemyMuzzle = transform.Find("EnemyMuzzle");
}
void Update()
{
//move enemy rigidbody toward player
Vector3 lookDirection = (player.transform.position - transform.position).normalized;
enemyRb.AddForce(lookDirection * speed);
//overallSpeed
Vector3 horizontalVelocity = enemyRb.velocity;
horizontalVelocity = new Vector3(enemyRb.velocity.x, 0, enemyRb.velocity.z);
// turns enemy to look at player
transform.LookAt(player.transform);
//launches projectile toward player
projectilePrefab.transform.Translate(lookDirection * speed * Time.deltaTime);
Instantiate(projectilePrefab, transform.position, projectilePrefab.transform.rotation);
}
public virtual void Fire()
{
canFire = false;
if (Time.time < nextFireAllowed)
return;
nextFireAllowed = Time.time + rateOfFire;
//instantiate the projectile;
Instantiate(projectilePrefab, enemyMuzzle.position, enemyMuzzle.rotation);
canFire = true;
}
}
解决方案
看起来实际发生的事情是您创建了一堆子弹,但没有存储对它们的引用。因此,当敌人靠近玩家时,每颗子弹都位于一个位置(这可能会让人觉得子弹相对于敌人移动。)我还假设敌人移动得非常快,因为它没有按增量时间缩放,而是每一帧都在更新。
我认为 projectilePrefab 只是您正在生成的模板对象,因此您可能不想直接移动它,当然也不想每帧都实例化一个新子弹。
如果您想移动您从示例代码中生成的最小更改(但仍然存在问题)的对象,则可能是:
public class EnemyController : MonoBehaviour
{
// add a reference
private GameObject projectileGameObject = null;
void Update()
{
//Update position of spawned projectile rather than the template
if(projectileGameObject != null ) {
projectileGameObject.transform.Translate(lookDirection * speed * Time.deltaTime);
}
// Be sure to remove this extra instantiate
//Instantiate(projectilePrefab, transform.position, projectilePrefab.transform.rotation);
}
public virtual void Fire()
{
//instantiate the projectile
projectileGameObject = Instantiate(projectilePrefab, enemyMuzzle.position, enemyMuzzle.rotation);
}
}
或者在一个列表中保留多个项目符号。这个实现有一个错误,它总是使用当前敌人到玩家的向量作为方向,而不是它被发射时存在的方向。
您最终可能想要的是每个射弹都有自己的类脚本来处理射弹逻辑。所有enemyController 类所要做的就是生成射弹并将其方向和位置设置在一个单独的monobehavior 上,该monobehavior 位于处理它自己的更新的Projectile 对象上。
推荐阅读
- python - 熊猫在没有分配的情况下更改 DataFrame 中的行
- r - RMarkdown - 更改内联代码颜色
- java - 如何在java中读取文本文件?
- mysql - Mysql百分比计算
- animation - 如何在 SVG.js 中暂停循环动画?
- vaadin - 带图像的 Vaadin 水平菜单栏
- makefile - Makefile递归安装?
- scala - 使用两个不同目录中的 Header 和 Data 创建 DataFrame / Dataset
- java - 来自 CameraUpdateFactory 的空对象引用导致的致命错误
- c++ - 使用 Clion 编译 SOIL