如何让射弹射向游戏对象
本文关键字:游戏 对象 | 更新日期: 2023-09-27 18:33:28
我目前正在研究TurretAi。我有它,当敌人在一定范围内时,炮塔瞄准敌人,但我无法让炮塔向敌人发射弹丸。这是我目前拥有的炮塔类。
using UnityEngine;
using System.Collections;
public class Defence : MonoBehaviour {
public float DistanceFromCastle,CoolDown;
public GameObject enemy;
public GameObject Bullet;
public int protectionRadius,bulletSpeed;
// Use this for initialization
void Start ()
{
protectionRadius = 35;
bulletSpeed = 50;
CoolDown = 5;
}
// Update is called once per frame
void Update () {
enemy = GameObject.FindGameObjectWithTag("Enemy");
if(enemy != null)
{
DistanceFromCastle = Vector3.Distance(GameObject.FindGameObjectWithTag("Enemy").transform.position,GameObject.FindGameObjectWithTag("Defence").transform.position);
//print (DistanceFromCastle);
if(DistanceFromCastle <= protectionRadius)
{
attackEnemy();
}
}
}
void attackEnemy()
{
transform.LookAt(enemy.transform);
CoolDown -= Time.deltaTime;
if (CoolDown <= 0)
{
Debug.DrawLine(transform.position,enemy.transform.position,Color.red);
Instantiate(Bullet,Vector3.forward,Quaternion.identity);
print("attack Enemy");
CoolDown = 5;
}
}
}
我也已经有一个冷却变量,所以它每 5 秒只拍摄一次任何帮助都会很棒。
你已经相当接近了,你需要改变这一行:
Instantiate(Bullet, Vector3.forward, Quaternion.identity);
对此:
private const int SPAWN_DISTANCE = 5;
Instantiate(Bullet, transform.position + SPAWN_DISTANCE * transform.forward, transform.rotation);
Quaternion.identity是指:
这个四元数对应于"无旋转"。