본문 바로가기
유니티강좌

2D 캐릭터 점프와 이동 구현 + 씬(무대)화면 디자인. 유니티 C# 스크립트 기초 강좌. (Unity Tutorial - Jump and move & Scene Design)

by Ncube 2020. 11. 27.

 

 

씬 화면(배경 / 방해물 / 캐릭터)을 디자인하고, 스프라이트 렌더러의 레이어 정렬. Edge Collider 2D, Capsule Collider 2D, Rigidbody 2D를 사용해 봅니다. Unity C# Script(Jump & Move) / Scene Design

 

Rigidbody2D - Constraints

Freeze Position 해당 축의 이동을 잠그는 기능

Freeze Rotation 해당 축의 회전을 잠그는 기능

 

RigidBody2D - Collision Detection

 

Discrete : (기본값)

Fixed delta time 단위로 1번씩 충돌 체크. (불연속 충돌 체크) 충돌 체크 횟수가 적으므로 당연히 Continuous 보다 성능상 빠름. Fixed Frame에 한번씩 충돌 여부를 체크하므로 속도가 빠르게 움직이는 Rigidbody 인 경우, Collider를 뚫고가는 현상 발생 할 수 있음.

 

Continuous : (빠르게 움직이는 Rigidbody object에 사용)

dynamic collider* 와 충돌할 때는 discrete와 동일하게 fixed delta time 단위로 충돌 체크하고, static mech collider* 와 충돌할 때는 연속적인 충돌 체크. 빠르게 움직이는 "총알"같은 rigidbody 오브젝트는 Continuous로 설정해야 벽 등을 통과하지 않음.

 

 

[CODE]

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayControl : MonoBehaviour
{
    float moveX;

    Rigidbody2D rb;

    [Header("이동 속도")]
    [SerializeField] [Range(100f, 800f)] float moveSpeed = 200f;

    [Header("점프 강도")]
    [SerializeField] [Range(100f, 800f)] float jumpForce = 400f;

    public AudioSource mySfx;

    public AudioClip jumpSfx;

    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        moveX = Input.GetAxis("Horizontal") * moveSpeed * Time.deltaTime;
        rb.velocity = new Vector2(moveX, rb.velocity.y);

        if (Input.GetKeyDown(KeyCode.Space))
        {
            if(rb.velocity.y == 0)
            {
                rb.AddForce(new Vector2(0, jumpForce), ForceMode2D.Force);

                JumpSound();
            }
        }
    }

    public void JumpSound()
    {
        mySfx.PlayOneShot(jumpSfx);
    }
}

 

댓글