73 lines
2.9 KiB
C#
73 lines
2.9 KiB
C#
using UnityEngine;
|
||
using RR.Game2D.Entities.Projectiles;
|
||
|
||
namespace RR.Game2D.Behaviour
|
||
{
|
||
public class PlayerFireScript : MonoBehaviour
|
||
{
|
||
[Header("Снаряд")]
|
||
[SerializeField] private PickableProjectile projectilePrefab;
|
||
public bool spawnIfMissing = false;
|
||
|
||
[Header("Бросок / Подбор")]
|
||
[SerializeField] private KeyCode actionKey = KeyCode.F;
|
||
[SerializeField] private float throwSpeed = 20f;
|
||
public Transform attachPoint;
|
||
|
||
private PickableProjectile pickableProjectile;
|
||
|
||
void Awake()
|
||
{
|
||
if (!attachPoint)
|
||
Debug.LogWarning("PlayerFireScript: attachPoint не задан. Будет использован корень игрока.");
|
||
}
|
||
|
||
void Update()
|
||
{
|
||
if (!Input.GetKeyDown(actionKey)) return;
|
||
|
||
if (pickableProjectile == null)
|
||
pickableProjectile = PickableProjectile.Instance;
|
||
|
||
if (pickableProjectile == null)
|
||
{
|
||
if (!spawnIfMissing || projectilePrefab == null)
|
||
{
|
||
Debug.LogError("PlayerFireScript: projectile missing; enable spawnIfMissing and assign projectilePrefab.");
|
||
return;
|
||
}
|
||
|
||
Vector3 spawnPos = attachPoint ? attachPoint.position : transform.position;
|
||
pickableProjectile = Instantiate(projectilePrefab, spawnPos, Quaternion.identity);
|
||
pickableProjectile.TryPickup(gameObject, attachPoint);
|
||
return;
|
||
}
|
||
// Бросок
|
||
if (pickableProjectile.CurrentState == PickableProjectile.State.Held && pickableProjectile.owner == gameObject) Throw();
|
||
}
|
||
|
||
/// <summary>
|
||
/// Метод для броска снаряда (выстрела).
|
||
/// У снаряда обязательно должен быть метод Launch(Vector2 direction)
|
||
/// </summary>
|
||
private void Throw()
|
||
{
|
||
float scaleX = transform.localScale.x;
|
||
float facing = Mathf.Sign(scaleX == 0 ? 1 : scaleX);
|
||
Vector2 direction = facing > 0 ? Vector2.right : Vector2.left;
|
||
Vector2 launchPos = (Vector2)transform.position + new Vector2(1.4f * facing, 0);
|
||
|
||
Vector3 projectileScale = pickableProjectile.transform.localScale;
|
||
pickableProjectile.transform.localScale = new Vector3(Mathf.Abs(projectileScale.x) * -facing, projectileScale.y, projectileScale.z);
|
||
|
||
pickableProjectile.transform.position = launchPos;
|
||
pickableProjectile.Launch(direction, throwSpeed, gameObject);
|
||
}
|
||
|
||
/// <summary>
|
||
/// Метод для привязки снаряда к игроку.
|
||
/// </summary>
|
||
/// <param name="proj">Снаряд</param>
|
||
public void BindProjectile(PickableProjectile proj) => pickableProjectile = proj;
|
||
}
|
||
} |