在我的游戏中,我有发射激光的飞船,我使用 ObectPool 进行了射击,但激光方向错误。我通过添加 RelativeForce 让它们移动,但它们会横向向前移动。我尝试用 _placeToSpawn.transform 而不是它的位置来实例化对象,但实例化的对象是 Ship 的孩子,当船移动时,激光也会移动。如何正确设置激活激光的受力方向?
对象池代码:
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
public class ObjectPool : MonoBehaviour
{
[SerializeField] private GameObject _placeToSpawn;
[SerializeField] private int _amount;
private List<GameObject> _pool = new();
protected void Initialize(GameObject prefab)
{
for (int i = 0; i < _amount; i++)
{
GameObject spawned = Instantiate(prefab, _placeToSpawn.transform.position, Quaternion.identity);
spawned.SetActive(false);
_pool.Add(spawned);
}
}
protected bool TryGetObject(out GameObject result)
{
result = _pool.FirstOrDefault(gameObject => gameObject.activeSelf == false);
return result != null;
}
}
从 ObjectPool 代码中运送射击对象:
using UnityEngine;
[RequireComponent(typeof(AudioSource))]
public class ShipShooter : ObjectPool
{
[SerializeField] private UIdata _score;
[SerializeField] private GameObject _laser;
[SerializeField] private AudioClip _shootAudio;
[SerializeField] private AudioSource _indestructibleSource;
[SerializeField] private float _laserSpeed;
[SerializeField] private float _laserShootVolume;
private AudioSource _source;
private bool _laserShooted = false;
private void Start()
{
Initialize(_laser);
_source = GetComponent<AudioSource>();
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
CreateLaser();
}
}
private void CreateLaser()
{
if (TryGetObject(out GameObject laser))
{
SetLaser(laser);
}
}
private void SetLaser(GameObject laser)
{
laser.SetActive(true);
laser.transform.SetPositionAndRotation(transform.position, transform.rotation);
laser.GetComponent<Rigidbody2D>().AddRelativeForce(Vector2.up * _laserSpeed);
laser.GetComponent<Laser>().score = _score;
laser.GetComponent<Laser>().source = _indestructibleSource;
_source.PlayOneShot(_shootAudio, _laserShootVolume);
_laserShooted = false;
}
}