스토리지

[4.6] 점프 게임 본문

Unity/유니티 기본

[4.6] 점프 게임

ljw4104 2021. 4. 6. 16:23

Physics

  • Physics을 사용하면 오브젝트를 간단하게 물리 동작에 맞춰 움직일 수 있다.
  • Rigidbody 컴포넌트(중력이나 마찰 등의 힘 계산) 와 Collider 컴포넌트(충돌판정 계산)으로 이루어져있다.
  • 자유롭게 이동하는 액션게임이나 복잡한 충돌 판정이 필요한 슈팅게임에 이상적임.

1. 구름과 캐릭터 배치 후 RigidBody 2d 및 Collider 2d 설치

둘 다 Rigidbody와 각각의 형체에 맞는 Collider를 맞춰주었다.
둘 다 떨어진다.

  • 캐릭터에는 물론, 구름에도 중력이 적용되었기 때문에 둘 다 떨어진다.
  • 구름의 Rigidbody 의 속성에 Body Type을 Kinematic으로 설정해줌으로서 중력이 적용 안되게 한다.

구름의 Collider와 플레이어의 Collider가 만나 더이상 떨어지지 않고 멈춰있다.

 

2. PlayerController 작성

  • Physics를 사용하므로 이동하는데 직접 좌표를 변경하지 않고, Physics를 사용하여 이동할 수 있다.
  • Rigidbody의 메소드 중에선 AddForce라고 하는 그 방향으로 힘을 주는 메소드를 사용해서 이동할 수 있다.
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    private Rigidbody2D rigid2D;

    public float jumpForce = 380.0f;
    public float walkForce = 20.0f;
    public float maxWalkSpeed = 2.0f;
    // Start is called before the first frame update
    void Start()
    {
        this.rigid2D = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            this.rigid2D.AddForce(transform.up * this.jumpForce);
        }

        //방향을 파악
        int dir = 0;
        if (Input.GetKey(KeyCode.LeftArrow)) dir = -1;
        if (Input.GetKey(KeyCode.RightArrow)) dir = 1;

        float speedx = Mathf.Abs(this.rigid2D.velocity.x);

        if(speedx < this.maxWalkSpeed)
        {
            this.rigid2D.AddForce(transform.right * dir * this.walkForce);
        }

        //가는 방향에따라 캐릭터의 시선처리
        if(dir != 0)
        {
            transform.localScale = new Vector3(dir, 1, 1);
        }
    }
}

 

3. 걷는 애니메이션 삽입

Sprite 이미지를 사용하여 Walk 모션 삽입하기

Animation관련부분은 찾아봐야됨.....

 

 

4. 카메라가 캐릭터를 따라가게 하기

만약 캐릭터가 맵 아주위쪽까지, 카메라 밖에까지 갔으면 카메라가 잡을 수 없다. 

그러므로 카메라의 y좌표는 캐릭터의 y좌표를 따라가게 한다.

using UnityEngine;

public class CameraController : MonoBehaviour
{
    private GameObject player;
    // Start is called before the first frame update
    void Start()
    {
        this.player = GameObject.Find("cat");
    }

    // Update is called once per frame
    void Update()
    {
        Vector3 playerPos = this.player.transform.position;
        transform.position = new Vector3(transform.position.x, playerPos.y, transform.position.z);
    }
}

* 스크립트를 이용하지 않고 카메라가 캐릭터를 따라가게 하는 법

자식 오브젝트는 부모 오브젝트의 좌표를 따라간다...

 

 

5. 깃발과 캐릭터간의 충돌 판정

  • Collision : 캐릭터와 오브젝트간의 충돌을 판정하는데 부딪히는 판정이 난다.
  • OnCollisionEnter라는 함수를 사용해서 판별한다.
  • Trigger : 캐릭터와 오브젝트간의 충돌을 판정하지만 통과한다. Collider의 Is Trigger에 체크하면 된다.
  • OnTriggerEnter라는 함수를 사용해서 판별한다.

 

6. Scene 간의 이동

using UnityEngine.SceneManager;

SceneManager.LoadScene("씬이름");

 

 

Comments