일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
- 크래프톤 정글랩
- Unity 독학
- 게임 개발 독학
- 크래프톤 정글 게임랩
- node.js
- unity 공부
- 크래프톤
- 오픽 im1
- unity 게임 개발
- unity 설치
- 유니티 대화
- 게임 개발
- 유니티
- 크래프톤 정글 게임 랩
- 오픽 im1 5일
- 게임 독학
- protobuf란
- 유니티 체스
- unity 게임
- protobuf 란?
- unity 강의
- 유니티 독학
- Unity Chess
- unity
- 유니티 퀘스트
- 크래프톤 게임 정글 랩
- unity 개발
- ETRI 연구연수
- 유니티 미연시
- 유니티 스토리
- Today
- Total
하참이의 아이디어노트
Unity 강의 5일차 (1) - 점프 게임 환경 설정 본문
본 강의는 다음 문서를 참고하여 제작하였습니다. 자세한 내용은 하단 링크를 참조하시거나 댓글로 질문 남겨주시면 성심성의껏 답변 드리겠습니다.
3.1강 - 점프력 - Unity Learn
개요: 이 수업의 목표는 이 프로토타입에 활용할 기본 게임플레이를 설정하는 것입니다. 먼저 새로운 Unity 프로젝트를 만들고 시작용 파일을 임포트합니다. 그런 다음 아름다운 배경과 플레이어
learn.unity.com
Unity에서 새 프로젝트를 생성합니다.
다음 주소로 파일을 다운받고 압축을 해제 한 뒤, 안의 패키지 파일을 임포트합니다.
Scenes폴더의 Prototype3 씬을 열고 SampleScene을 저장하지 않고 삭제합니다.
Layout을 2 by 3으로 해두는 것을 권장합니다.
캐릭터를 하나 생성합시다. Course Library -> Characters에서 Farm, Town 중 원하는 폴더를 선택하고 캐릭터를 추가합니다. 하이어라키 창으로 드래그 하면 쉽게 생성됩니다.
Y축으로 회전하여 오른쪽을 바라보게 만듭니다.
이름을 Player라고 변경합니다.
Player에게 Rigidbody와 Box Collider 컴포넌트를 추가합니다.
Player의 Collider를 편집합니다.
Assets 하위에 Scripts 폴더를 생성하고 PlayerController 스크립트를 생성합니다.
스크립트의 생성이 완료되면 Player에게 컴포넌트를 부착하는 것을 잊지 맙시다.
이제 점프를 구현해봅시다.
PlayerController를 다음과 같이 작성합니다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private Rigidbody playerRb;
// Start is called before the first frame update
void Start()
{
playerRb = GetComponent<Rigidbody>();
playerRb.AddForce(Vector3.up * 1000);
}
// Update is called once per frame
void Update()
{
}
}
위 코드에서 중요한 것은 Rigidbody라는 변수를 선언하고 사용함을 이해하는 것 입니다.
Unity에서의 컴포넌트는 변수로 선언 할 수 있습니다. 따라서 전역에 Rigidbody playerRb를 선언해주었습니다.
그리고 Start에서 GetComponent<Rigidbody>()를 이용하여 해당 스크립트 컴포넌트가 할당될 게임 오브젝트가 가지고 있는 Rigidbody 컴포넌트에 대한 정보를 가져옵니다. 즉 Player에게 할당한 Rigidbody가 playerRb에게 할당되었다고 볼 수 있겠네요.
이와 같이 변수에 대한 선언은 전역에, 변수의 할당은 Start() 함수에서 처리하는 것을 권장드립니다.
게임을 시작하면 Player가 점프하는 것을 볼 수 있습니다.
하지만 이는 Start 함수에서 한번 선언해 준 것이기 때문에 저희가 조작했던 것이 아니지요.
스페이스바를 누르면 점프하는 방식으로 변경해봅시다.
다음과 같이 코드를 수정합니다. 키를 누르면 작동하는 방식에 대해서는 이전 시간에 여러 번 배웠으니 한 번 직접 작성해보시는 것을 권장합니다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private Rigidbody playerRb;
// Start is called before the first frame update
void Start()
{
playerRb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
playerRb.AddForce(Vector3.up * 1000);
}
}
}
점프가 바로 되지 않는 것 같네요. 이럴경우 AddForce에는 ForceMode 열거형을 받을 수 있는 오버로드가 따로 존재합니다.
다음과 같이 함수를 수정합니다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private Rigidbody playerRb;
// Start is called before the first frame update
void Start()
{
playerRb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
playerRb.AddForce(Vector3.up * 10, ForceMode.Impulse);
}
}
}
ForceMode를 곱하기만 하면 점프가 바로 적용되는 대신 점프가 멈추지 않더군요. 곱하는 상수를 10으로 변경하여 수정합니다.
이제 하드코딩 되어있던 부분을 수정하고, Inspector창에서 변수를 조정 할 수 있도록 변경합니다.
다음과 같이 작성합니다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private Rigidbody playerRb;
public float jumpForce = 10;
public float gravityModifier = 1;
// Start is called before the first frame update
void Start()
{
playerRb = GetComponent<Rigidbody>();
Physics.gravity *= gravityModifier;
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
playerRb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
}
}
}
흠... 그럼에도 문제가 발생하네요. 캐릭터가 점프상태인데도 스페이스바를 누르면 무한으로 점프하는 버그가 있습니다.
코드를 다음과 같이 수정해봅시다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private Rigidbody playerRb;
public float jumpForce = 10;
public float gravityModifier = 1;
public bool isOnGround = true;
// Start is called before the first frame update
void Start()
{
playerRb = GetComponent<Rigidbody>();
Physics.gravity *= gravityModifier;
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && isOnGround)
{
playerRb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
isOnGround = false;
}
}
private void OnCollisionEnter(Collision collision)
{
isOnGround = true;
}
}
OnCollisionEnter를 설정하여 땅에 닿기 전에는 점프 불가능 상태로 바꾸었습니다.
(하지만 이 경우는 다른 장애물과 닿아도 점프를 한 번 더 할 수 있는 버그가 될 수 있겠네요.)
다음은 장애물을 만들어보겠습니다.
Obstacles 폴더 안의 임의의 장애물 하나를 하이어라키 창으로 드래그 한 뒤 이름을 Obstacle로 변경합니다.
장애물도 충돌 판정을 만들기 위해 BoxCollider 컴포넌트를 추가해준 뒤 Collider를 수정해줍니다.
장애물을 여러개 만들기 위해 프리팹화 합니다. Assets에 Prefabs 폴더를 생성하고 Obstacle을 드래그해 프리팹화 합니다.
장애물이 왼쪽으로 날라오는 스크립트를 작성해봅시다.
Scripts 폴더에 MoveLeft 스크립트를 생성하고 다음과 같이 작성합니다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveLeft : MonoBehaviour
{
private float speed = 30;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.Translate(Vector3.left * Time.deltaTime * speed);
}
}
특이한 내용이 없으니 설명은 생략하겠습니다. 해당 스크립트 컴포넌트를 Obstacle 프리팹에 부착합니다.
이제 SpawManager를 제작합시다. 빈 게임 오브젝트를 생성하고 이름을 SpawnManager로 설정합니다.
SpawnManager 스크립트를 생성하고 SpawnManager게임 오브젝트에 컴포넌트로 붙입니다.
그리고 다음과 같이 작성합니다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnManager : MonoBehaviour
{
public GameObject obstaclePrefab;
private Vector3 spawnPos = new Vector3(25, 0, 0);
private float startDelay = 2;
private float repeatRate = 2;
// Start is called before the first frame update
void Start()
{
InvokeRepeating("SpawnObstacle", startDelay, repeatRate);
}
void SpawnObstacle()
{
Instantiate(obstaclePrefab, spawnPos, obstaclePrefab.transform.rotation);
}
// Update is called once per frame
void Update()
{
}
}
이것 역시 설명을 생략하겠습니다.
'Unity > Unity 기초' 카테고리의 다른 글
Unity 강의 5일차 (3) - 캐릭터 애니메이션 (2) | 2025.01.20 |
---|---|
Unity 강의 5일차 (2) - 점프 게임 디테일 추가 (0) | 2025.01.20 |
Unity 강의 4일차 (1) - 물어 오기 놀이 (0) | 2025.01.17 |
Unity 강의 3일차 (4) - 피자 날리기 게임 4 (0) | 2025.01.17 |
Unity 강의 3일차 (3) - 피자 날리기 게임 3 (0) | 2025.01.17 |