Danro/Assets/Resources/Scripts/Behaviour/PlayerFireScript.cs

85 lines
2.6 KiB
C#

using Projectiles2D;
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()
{
var proj = P;
if (proj != null && proj.CurrentState != PickableProjectile.State.Held)
{
Vector3 grabFrom = attachPoint ? attachPoint.position : transform.position;
float dist = Vector2.Distance(proj.transform.position, grabFrom);
if (dist <= pickupRadius)
{
proj.TryPickup(gameObject, attachPoint);
return;
}
}
if (!Input.GetKeyDown(actionKey)) return;
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;
Vector2 launchPos = (Vector2)transform.position + new Vector2(1.4f * facing, 0f);
proj.transform.localScale = new Vector3(-facing * proj.transform.localScale.x, proj.transform.localScale.y, proj.transform.localScale.z);
proj.transform.position = launchPos;
proj.Launch(dir, throwSpeed, gameObject);
return;
}
}
#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
}