유니티 상에서 플레이어가 사망 시 fastapi로 전달하여 db에 데이터 추가

This commit is contained in:
김민구
2026-07-03 18:20:32 +09:00
parent 7f2e3101a7
commit 83bc9e3200
4 changed files with 80 additions and 14 deletions
+49 -6
View File
@@ -125,21 +125,22 @@ public class PlayerMove : MonoBehaviour
}
// 데미지를 입는 메서드
public void TakeDamage(int damage)
public void TakeDamage(int damage, string attackerName = "알 수 없는 위험")
{
if (hp <= 0) return; // 이미 사망한 경우 제외
hp -= damage;
if (hp < 0) hp = 0;
Debug.Log($"플레이어가 {damage} 데미지를 입었습니다. 현재 체력: {hp}");
Debug.Log($"플레이어가 {attackerName}로부터 {damage} 데미지를 입었습니다. 현재 체력: {hp}");
if (animator != null)
{
if (hp <= 0)
{
animator.SetTrigger("4_Death");
Debug.Log("플레이어가 사망했습니다.");
Debug.Log($"플레이어가 {attackerName}에 의해 사망했습니다.");
StartCoroutine(SendDeathReport(attackerName));
}
else
{
@@ -152,7 +153,7 @@ public class PlayerMove : MonoBehaviour
[ContextMenu("Debug/Take 5 Damage")]
public void DebugTake5Damage()
{
TakeDamage(5);
TakeDamage(5, "인스펙터 디버그 공격");
}
[ContextMenu("Debug/Restore HP")]
@@ -171,9 +172,16 @@ public class PlayerMove : MonoBehaviour
private void OnGUI()
{
GUI.backgroundColor = Color.red;
if (GUI.Button(new Rect(10, 10, 180, 50), "Debug: Take 5 Damage"))
if (GUI.Button(new Rect(10, 10, 180, 50), "Debug: Take 5 Damage (Trap)"))
{
TakeDamage(5);
TakeDamage(5, "테스트 함정");
}
GUI.backgroundColor = Color.blue;
// 기존 겹쳐있던 위치(10, 10)를 피해 y 좌표를 130으로 내렸습니다.
if (GUI.Button(new Rect(10, 130, 180, 50), "Debug: Take 3 Damage (Monster)"))
{
TakeDamage(3, "테스트 몬스터");
}
GUI.backgroundColor = Color.green;
@@ -182,4 +190,39 @@ public class PlayerMove : MonoBehaviour
DebugRestoreHP();
}
}
// 백엔드로 사망 원인을 전송하는 코루틴
private System.Collections.IEnumerator SendDeathReport(string cause)
{
string url = "http://127.0.0.1:8000/api/game/death";
DeathRecordRequest requestData = new DeathRecordRequest { cause_of_death = cause };
string json = JsonUtility.ToJson(requestData);
using (UnityEngine.Networking.UnityWebRequest request = new UnityEngine.Networking.UnityWebRequest(url, "POST"))
{
byte[] bodyRaw = System.Text.Encoding.UTF8.GetBytes(json);
request.uploadHandler = new UnityEngine.Networking.UploadHandlerRaw(bodyRaw);
request.downloadHandler = new UnityEngine.Networking.DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
yield return request.SendWebRequest();
if (request.result == UnityEngine.Networking.UnityWebRequest.Result.ConnectionError ||
request.result == UnityEngine.Networking.UnityWebRequest.Result.ProtocolError)
{
Debug.LogError("사망 기록 전송 실패: " + request.error);
}
else
{
Debug.Log("사망 기록 전송 성공: " + request.downloadHandler.text);
}
}
}
}
// JSON 파싱용 요청 스키마 객체
[System.Serializable]
public class DeathRecordRequest
{
public string cause_of_death;
}