79 lines
2.4 KiB
C#
79 lines
2.4 KiB
C#
using UnityEngine;
|
||
|
||
public class PlayerFireScript : MonoBehaviour
|
||
{
|
||
[Header("Projectile (single instance)")]
|
||
[SerializeField] public PickableProjectile projectilePrefab;
|
||
public bool spawnIfMissing = true;
|
||
|
||
[Header("Throw / Pickup")]
|
||
public Transform attachPoint;
|
||
public KeyCode actionKey = KeyCode.F;
|
||
public float throwSpeed = 20f;
|
||
public float pickupRadius = 1.2f;
|
||
|
||
private PickableProjectile P => PickableProjectile.Instance;
|
||
|
||
void Awake()
|
||
{
|
||
if (!attachPoint)
|
||
{
|
||
var hand = transform.Find("HandPoint");
|
||
if (hand) attachPoint = hand;
|
||
}
|
||
}
|
||
|
||
void Update()
|
||
{
|
||
if (!Input.GetKeyDown(actionKey)) return;
|
||
|
||
var proj = P;
|
||
|
||
if (proj == null)
|
||
{
|
||
if (!spawnIfMissing || projectilePrefab == null)
|
||
{
|
||
Debug.Log("FireScript2D: projectile missing; set spawnIfMissing=true and assign projectilePrefab.");
|
||
return;
|
||
}
|
||
|
||
Vector3 spawnPos = attachPoint ? attachPoint.position : transform.position;
|
||
proj = Instantiate(projectilePrefab, spawnPos, Quaternion.identity);
|
||
proj.TryPickup(gameObject, attachPoint);
|
||
return;
|
||
}
|
||
|
||
if (proj.CurrentState == PickableProjectile.State.Held && proj.owner == gameObject)
|
||
{
|
||
float sx = transform.localScale.x;
|
||
float facing = Mathf.Sign(sx == 0 ? 1 : sx);
|
||
Vector2 dir = facing > 0 ? Vector2.right : Vector2.left;
|
||
|
||
proj.Launch(dir, throwSpeed, gameObject);
|
||
return;
|
||
}
|
||
|
||
Vector3 grabFrom = attachPoint ? attachPoint.position : transform.position;
|
||
float dist = Vector2.Distance(proj.transform.position, grabFrom);
|
||
|
||
if (proj.CurrentState != PickableProjectile.State.Held && dist <= pickupRadius)
|
||
{
|
||
proj.TryPickup(gameObject, attachPoint);
|
||
return;
|
||
}
|
||
|
||
// Не в радиусе подбора — ничего не делаем
|
||
// Debug.Log("FireScript2D: projectile is too far to pick up.");
|
||
}
|
||
|
||
#if UNITY_EDITOR
|
||
void OnDrawGizmosSelected()
|
||
{
|
||
// визуально показать радиус подбора
|
||
Gizmos.color = new Color(0.2f, 0.8f, 1f, 0.35f);
|
||
Vector3 center = attachPoint ? attachPoint.position : transform.position;
|
||
Gizmos.DrawWireSphere(center, pickupRadius);
|
||
}
|
||
#endif
|
||
}
|