본문 바로가기
유니티강좌

점프 후 접촉한 발판(플랫폼)이 떨어지고 다시 리스폰되는 발판 구현. How to make Respawn Platforms & Falling Platforms | 유니티 게임 개발 튜토리얼(Unity & C# Script)

by Ncube 2021. 1. 29.

 

 

캐릭터가 점프해서 발판에 닿으면 그 발판이 잠시 후 떨어지고 다시 발판이 리스폰되는 방법을 알아봅니다. 발판들을 딛고 지나가면 하나씩 떨어지고 떨어진 순서대로 차례로 하나씩 발판들이 리스폰됩니다.

 

 

[CharacterMove.cs]

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

public class CharacterMove : MonoBehaviour
{
    [SerializeField] float speed = 4f, jumpForce = 500f;
    float moveX;
    Rigidbody2D rb;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        Movement();
    }

    void Movement()
    {
        moveX = Input.GetAxis("Horizontal") * speed;

        if (Input.GetButtonDown("Jump") && rb.velocity.y == 0)
            rb.AddForce(Vector2.up * jumpForce);

        rb.velocity = new Vector2(moveX, rb.velocity.y);
    }
}

 

 

[FallingPlatforms.cs]

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

public class FallingPlatforms : MonoBehaviour
{
    [SerializeField] float fallTime = 0.5f, destroyTime = 2f;
    Rigidbody2D rb;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    void OnCollisionEnter2D(Collision2D col)
    {
        if (col.gameObject.name.Equals("Character"))
        {
            PlatformManager.Instance.StartCoroutine("spawnPlatform", 
                new Vector2(transform.position.x, transform.position.y));
            Invoke("FallPlatform", fallTime);
            Destroy(gameObject, destroyTime);
        }
    }

    void FallPlatform()
    {
        rb.isKinematic = false;
    }
}

 

 

[PlatformManager.cs]

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

public class PlatformManager : MonoBehaviour
{
    public static PlatformManager Instance = null;
    [SerializeField] GameObject platform;
    [SerializeField] float posX1, posX2, posX3, posY;
    [SerializeField] float spawnTime = 2f;

    void Start()
    {
        if (Instance == null)
            Instance = this;
        else if (Instance != this)
            Destroy(gameObject);

        Instantiate(platform, new Vector2(posX1, posY), platform.transform.rotation);
        Instantiate(platform, new Vector2(posX2, posY), platform.transform.rotation);
        Instantiate(platform, new Vector2(posX3, posY), platform.transform.rotation);
    }

    IEnumerator spawnPlatform(Vector2 spawnPos)
    {
        yield return new WaitForSeconds(spawnTime);
        Instantiate(platform, spawnPos, platform.transform.rotation);
    }
}

 

댓글