🕹️ 실습 (2D 횡스크롤 스테이트머신)
Skill
public class SkillManager : MonoBehaviour
{
public static SkillManager Instance;
public DashSkill dash { get; private set; }
public CloneSkill clone { get; private set; }
public SwordSkill sword { get; private set; }
private void Awake()
{
if (Instance != null)
{
Destroy(Instance);
}
else
{
Instance = this;
}
}
private void Start()
{
dash = GetComponent<DashSkill>();
clone = GetComponent<CloneSkill>();
sword = GetComponent<SwordSkill>();
}
}
public class Skill : MonoBehaviour
{
[SerializeField] protected float cooldown;
protected float cooldownTimer;
protected Player player;
protected virtual void Start()
{
player = PlayerManager.Instance.player;
}
protected virtual void Update()
{
cooldownTimer -= Time.deltaTime;
}
public virtual bool CanUseSkill()
{
if (cooldownTimer < 0)
{
cooldownTimer = cooldown;
return true;
}
else
{
Debug.Log("Skill is on cooldown");
return false;
}
}
public virtual void UseSkill()
{
}
}
SwordSkill - Sword 던지기
// SwordSkill.cs
[Header("Skill Info")]
[SerializeField] private GameObject swordPrefab;
[SerializeField] private Vector2 launchForce;
[SerializeField] private float swordGravity;
private Vector2 finalDir;
[Header("Aim Dots Info")]
[SerializeField] private int numberofDots;
[SerializeField] private float spaceBeetwenDots;
[SerializeField] private GameObject dotPrefab;
[SerializeField] private Transform dotsParent;
protected override void Update()
{
if (Input.GetKeyUp(KeyCode.Mouse1)) // 마우스 오른쪽 버튼을 뗄 때
{
Vector2 aimDirection = AimDirection(); // 조준 방향 계산
finalDir = new Vector2(aimDirection.normalized.x * launchForce.x,
aimDirection.normalized.y * launchForce.y); // 최종 발사 방향 결정
}
if (Input.GetKey(KeyCode.Mouse1)) // 마우스 오른쪽 버튼 누르고 있는 동안
{
// 점 위치로 계적 보여줌
for(int i=0; i<dots.Length; i++)
{
dots[i].transform.position = DotsPosition(i * spaceBeetwenDots);
}
}
}
public Vector2 AimDirection()
{
Vector2 playerPosition = player.transform.position;
Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 direction = mousePosition - playerPosition;
return direction;
}
public void DotsActive(bool _isActive)
{
for(int i=0; i<dots.Length; i++)
{
dots[i].SetActive(_isActive);
}
}
private void GenerateDots()
{
dots = new GameObject[numberofDots];
for(int i=0; i<numberofDots; i++)
{
dots[i] = Instantiate(dotPrefab, player.transform.position, Quaternion.identity, dotsParent);
dots[i].SetActive(false);
}
}
private Vector2 DotsPosition(float t) // 포물선 방향으로 점을 그려줌
{
Vector2 aimDirection = AimDirection();
Vector2 position = (Vector2)player.transform.position
+ new Vector2(aimDirection.normalized.x * launchForce.x, aimDirection.normalized.y * launchForce.y)
* t + 0.5f * (Physics2D.gravity * swordGravity) * (t * t);
return position;
}