74 lines
2.5 KiB
C#
74 lines
2.5 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;
|
|
|
|
private PickableProjectile pickableProj;
|
|
|
|
void Awake()
|
|
{
|
|
if (!attachPoint)
|
|
attachPoint = FindDeepChild(transform, "HandPoint");
|
|
|
|
if (!attachPoint)
|
|
Debug.LogWarning("PlayerFireScript: attachPoint не задан и HandPoint не найден. Будет использован корень игрока.");
|
|
}
|
|
|
|
void Update()
|
|
{
|
|
if (!Input.GetKeyDown(actionKey)) return;
|
|
|
|
if (pickableProj == null)
|
|
pickableProj = PickableProjectile.Instance;
|
|
|
|
if (pickableProj == null)
|
|
{
|
|
if (!spawnIfMissing || projectilePrefab == null)
|
|
{
|
|
Debug.Log("PlayerFireScript: projectile missing; enable spawnIfMissing and assign projectilePrefab.");
|
|
return;
|
|
}
|
|
|
|
Vector3 spawnPos = attachPoint ? attachPoint.position : transform.position;
|
|
pickableProj = Instantiate(projectilePrefab, spawnPos, Quaternion.identity);
|
|
pickableProj.TryPickup(gameObject, attachPoint);
|
|
return;
|
|
}
|
|
|
|
// Бросок
|
|
if (pickableProj.CurrentState == PickableProjectile.State.Held && pickableProj.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);
|
|
|
|
var s = pickableProj.transform.localScale;
|
|
pickableProj.transform.localScale = new Vector3(Mathf.Abs(s.x) * -facing, s.y, s.z);
|
|
|
|
pickableProj.transform.position = launchPos;
|
|
pickableProj.Launch(dir, throwSpeed, gameObject);
|
|
}
|
|
}
|
|
|
|
public void BindProjectile(PickableProjectile proj) => pickableProj = proj;
|
|
|
|
private Transform FindDeepChild(Transform parent, string name)
|
|
{
|
|
foreach (Transform child in parent)
|
|
{
|
|
if (child.name == name) return child;
|
|
var r = FindDeepChild(child, name);
|
|
if (r) return r;
|
|
}
|
|
return null;
|
|
}
|
|
} |