예제)고양이 구름 올라가기 게임
구현한 기능
- 충돌 감지
- 키 입력에 따른 고양이 이동
- 물리값 적용(ex. 중력)
- 고양이의 움직임에 따른 카메라 무빙
.
.
.
.
(1)CatController.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class CatController : MonoBehaviour
{
private Rigidbody2D rBody2D;
private float jumpForce = 7f;
private float moveForce = 30f;
private Animator anim;
// Start is called before the first frame update
void Start()
{
this.rBody2D = this.GetComponent<Rigidbody2D>();
this.anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space)&&this.rBody2D.velocity.y==0)
{
this.rBody2D.AddForce(Vector2.up*this.jumpForce, ForceMode2D.Impulse);
}
int dirX = 0;
if (Input.GetKey(KeyCode.LeftArrow))
dirX = -1;
if(Input.GetKey(KeyCode.RightArrow))
dirX = 1;
//ForceMode2D.Force : 지속적으로 힘을 가할때
//ForceMode2D.Impulse : 충격을 줘서 힘을 가할때
//Debug.Log(this.rBody2D.velocity.x);
float speedX = Mathf.Abs(this.rBody2D.velocity.x);
if (speedX < 2f)
{
//this.rBody2D.AddForce(new Vector2(dirX, 0) * this.moveForce);
this.rBody2D.AddForce(this.transform.right * dirX * this.moveForce);
}
if (dirX != 0)
{
this.transform.localScale = new Vector3(dirX, 1, 1);
}
//플레이어의 속도에 따라서 애니메이션의 속도를 바꾸자
this.anim.speed= speedX / 2.0f;
}
private void OnTriggerEnter2D(Collider2D collision)
{
Debug.Log("Game Clear씬으로 전환");
SceneManager.LoadScene("ClearScene");
}
}
대부분의 게임 구현을 실행시킨 코드.
고양이의 움직임과 충돌을 감지해준다.
(2) CameraDirector.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraDirector : MonoBehaviour
{
GameObject catGo;
GameObject cameraGo;
// Start is called before the first frame update
void Start()
{
this.catGo = GameObject.Find("cat");
this.cameraGo = GameObject.Find("Main Camera");
}
// Update is called once per frame
void Update()
{
if(this.catGo.transform.position.y>=0&&this.catGo.transform.position.y<2)
cameraGo.transform.position = new Vector3(0, catGo.transform.position.y, -10);
}
}
고양이의 움직임에 따라 카메라 무빙에 변화를 준다.
(3)ClearDirector.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class ClearDirector : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
SceneManager.LoadScene("GameScene");
}
}
}
게임을 클씬리어하고 등장하는 씬 삽입.
새로운 장면을 나타내기 위해서는 새로운 씬의 도입이 필요.
이 코드에서는 클리어씬에서 마우스 왼쪽 버튼을 클릭 시 다시 게임 시작되도록 구현되어 있다.
(4)결과
'K-digital traning > 유니티 기초' 카테고리의 다른 글
몬스터 처지 후 아이템 드롭 + 장착 (0) | 2023.08.10 |
---|---|
[주말과제] 이동 및 몬스터 공격 (0) | 2023.08.07 |
애니메이션 전환 연습 (0) | 2023.08.03 |
캐릭터 이동(달리기) 애니메이션 (0) | 2023.08.03 |
[수업과제] 표창 던지기 (0) | 2023.08.01 |