게임 개발 일지/유니티 엔진 공부
24. 유니티 2D 종스크롤 슈팅 - 플레이어 이동 구현
인텔리킴
2024. 5. 12. 18:47
플레이어 기본 이동 구현
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public float speed;
void Update()
{
float h = Input.GetAxisRaw("Horizontal");
float v = Input.GetAxisRaw("Vertical");
Vector3 curPos = transform.position;
Vector3 nextPos = new Vector3(h, v, 0) * speed * Time.deltaTime;
transform.position = curPos + nextPos;
}
}
* transform을 이용한 이동은 Time.DeltaTime 꼭 이용하기
기본적인 플레이어 이동 구현
해상도 조절
Free Aspect : 자유 비율 (카메라 크기 = 해상도 크기
자기가 직접 화면 비율을 조절해서 해상도 만들 수 있음
하지만 플레이어가 화면 밖으로 나가는 문제 있음
경계 설정
화면 경계쪽 4방향에 모두 Collider 생성
플레이어의 RigidBody2D 타입은 Kinematics
* Kinematics : 스크립트 내에서 설정한 움직임으로만 움직이게 함
Border의 RigidBody2D 타입은 Static
* Static : 물리 판정이 고정되있음 (움직이지 않음)
스크립트를 통해 Border에 플레이어가 닿으면 움직임이 멈추게 해야됨
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class Player : MonoBehaviour
{
public float speed;
public bool isTouchTop;
public bool isTouchBottom;
public bool isTouchLeft;
public bool isTouchRight;
void Update()
{
//왼쪽, 오른쪽 벽에 밀착하면 h = 0
float h = Input.GetAxisRaw("Horizontal");
if ((h == 1 && isTouchRight) || (h == -1 && isTouchLeft))
h = 0;
//위 아래 벽에 부딪히면 v = 0
float v = Input.GetAxisRaw("Vertical");
if ((v == 1 && isTouchTop) || (v == -1 && isTouchBottom))
v = 0;
Vector3 curPos = transform.position;
Vector3 nextPos = new Vector3(h, v, 0) * speed * Time.deltaTime;
transform.position = curPos + nextPos;
}
//트리거 시작할때
void OnTriggerEnter2D(Collider2D collision)
{
//경계선과 가까워지면
if (collision.gameObject.tag == "Border")
{
switch (collision.gameObject.name)
{
case "TopBorderLines":
isTouchTop = true;
break;
case "BottomBorderLines":
isTouchBottom = true;
break;
case "LeftBorderLines":
isTouchLeft = true;
break;
case "RightBorderLines":
isTouchRight = true;
break;
}
}
}
//트리거 빠져 나올때
void OnTriggerExit2D(Collider2D collision)
{
//경계선과 멀어지면
if (collision.gameObject.tag == "Border")
{
switch (collision.gameObject.name)
{
case "TopBorderLines":
isTouchTop = false;
break;
case "BottomBorderLines":
isTouchBottom = false;
break;
case "LeftBorderLines":
isTouchLeft = false;
break;
case "RightBorderLines":
isTouchRight = false;
break;
}
}
}
}
벽과 부딪히면 플래그를 true로 하고 벽과 멀어지면 플래그가 false가 되도록 함
플레이어 애니메이션
if (Input.GetButtonDown("Horizontal") || Input.GetButtonUp("Horizontal"))
{
animator.SetInteger("Horizontal", (int)h);
}
간단한 애니메이션 코드 사용
SetInteger로 움직일때 변수값 가져옴