오늘 한 일
오늘은 Flappybird게임과 비슷하게 게임을 짜봤습니다.
바로 코드부터 확인 들어가겠습니다.
//
Player.cs
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
public class Player : MonoBehaviour
{
Animator animator;
Rigidbody2D _rigidbody; //rigidbody는 unity에서 기본으로 제공되는건데 장애물과 부딪쳤을때 쓰는 용도 입니다.
public float flapForce = 6f;
public float forwardSpeed = 3f;
public bool isDead = false;
float deathCooldown = 0f;
bool isFlap = false;
public bool godMode = false;
void Start()
{
animator = GetComponentInChildren<Animator>();//animator를 가져와 줬는데 개체가 자식 부분이라서 InChildren을 사용해 자식도 확인할 수 있는 코드를 적었습니다
_rigidbody = GetComponent<Rigidbody2D>();
if (animator == null)
{
Debug.LogError("not found animator.");
}
if (_rigidbody == null)
{
Debug.LogError("not found Rigidbody2D.");
}
}
// Update is called once per frame
void Update()
{
if (isDead)
{
if (deathCooldown <= 0)
{
//게임 재시작
}
else
{
deathCooldown -= Time.deltaTime; //컴퓨터마다 프레임이 다를 수 있기 때문에 적용을 시켜줍니다
}
}
else
{
if (Input.GetKeyDown(KeyCode.Space) || Input.GetMouseButtonDown(0))
{
isFlap = true;
}
}
}
private void FixedUpdate() //여기서는 물리계산을 해줍니다.
{
if (isDead) return;
Vector3 velocity = _rigidbody.velocity;
velocity.x = forwardSpeed;
if (isFlap)
{
velocity.y += flapForce;
isFlap = false;
}
_rigidbody.velocity = velocity;
float angle = Mathf.Clamp((_rigidbody.velocity.y * 10f), -90, 90);
transform.rotation = Quaternion.Euler(0, 0, angle);
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (godMode) return;
if (isDead) return;
isDead = true;
deathCooldown = 1f;
animator.SetInteger("isDie", 1);
//게임오버 처리
}
}
animaot에서는 어떤 작업을 하였는지 말해드리겠습니다.
-> flap, die라는 animator를 만든 뒤에 사진을 죽었을때와 살아있을때의 이미지를 추가해줍니다.
-> 다음으로 Transition을 추가해 Entry에서 flap으로 다음은 die로 이어지게 추가해줍니다.
->그리고 Parameters에 isDie를 추가해 작동시켜 주며 연결을 시켜주면 됩니다!
truoble shooting)
-문제발생-
⚠️ 'Model' AnimationEvent has no function name specified! 경고 라는 문구가 계속 출력 (장애물에 부딪혀도 색깔이 바꾸지 않는 현상)
-문제해결-
코드부문에서는 문제가 없고, animator에서 문제를 찾기 시작함
-결과-
animator에서 스스로 생성한 null상태인 이벤트점이 추가가 되어있는 상태였음. delete를 하니 바로 해결이 됨.