티스토리 뷰

슈퍼 마리오와 같은 플랫포머 게임을 유니티로 구현하기 위한 전체적인 소스 코드는 매우 방대하고 복잡합니다. 그러나 간단한 플랫포머 게임의 기본 구조와 몇 가지 예시 코드를 제공할 수 있습니다. 아래는 플레이어 캐릭터의 이동, 점프, 아이템 수집 및 적과의 충돌 등을 다루는 간단한 플랫포머 게임의 예시 소스 코드입니다.

 

using UnityEngine;

public class PlayerController : MonoBehaviour
{
    public float moveSpeed = 5f;
    public float jumpForce = 5f;
    public Transform groundCheck;
    public LayerMask groundLayer;
    public GameObject bulletPrefab;
    public Transform firePoint;

    private bool isJumping = false;
    private bool isGrounded = false;
    private Rigidbody2D rb;
    private Animator animator;

    private void Awake()
    {
        rb = GetComponent<Rigidbody2D>();
        animator = GetComponent<Animator>();
    }

    private void Update()
    {
        float moveInput = Input.GetAxis("Horizontal");
        rb.velocity = new Vector2(moveInput * moveSpeed, rb.velocity.y);

        if (moveInput != 0)
        {
            transform.localScale = new Vector3(Mathf.Sign(moveInput), 1f, 1f);
            animator.SetBool("isRunning", true);
        }
        else
        {
            animator.SetBool("isRunning", false);
        }

        isGrounded = Physics2D.OverlapCircle(groundCheck.position, 0.2f, groundLayer);

        if (isGrounded)
        {
            isJumping = false;
            animator.SetBool("isJumping", false);
        }

        if (Input.GetButtonDown("Jump") && isGrounded && !isJumping)
        {
            rb.AddForce(new Vector2(0f, jumpForce), ForceMode2D.Impulse);
            isJumping = true;
            animator.SetBool("isJumping", true);
        }

        if (Input.GetButtonDown("Fire1"))
        {
            FireBullet();
        }
    }

    private void FireBullet()
    {
        Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag("Enemy"))
        {
            // Handle player-enemy collision
            Die();
        }
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.CompareTag("Collectible"))
        {
            // Handle item collection
            Destroy(collision.gameObject);
        }
    }

    private void Die()
    {
        // Handle player death
    }
}

위의 코드는 PlayerController 스크립트로서 플레이어 캐릭터의 움직임, 점프, 총알 발사, 충돌 처리 등을 다룹니다. Update() 메서드에서는 사용자 입력을 받아 플레이어 캐릭터의 이동을 처리하고, 점프를 감지하며, 총알 발사를 처리합니다. 또한, 플레이어와 적 또는 아이템과의 충돌을 감지하고 적과의 충돌 시 플레이어의 사망을 처리합니다.

이 코드 예시는 단일 캐릭터의 움직임 및 기본적인 상호작용에 대한 것이며, 실제 게임에는 더 많은 기능과 요소들이 필요할 수 있습니다. 더 복잡한 플랫포머 게임을 구현하기 위해서는 레벨 디자인, 플레이어 상태 관리, 다양한 아이템 및 적의 동작 패턴, 물리 시뮬레이션, 사운드 효과 등을 고려해야 합니다. 이 예시 코드는 시작점으로 활용하여 게임을 보다 발전시킬 수 있습니다.

댓글
최근에 달린 댓글
글 보관함
«   2024/05   »
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
Total
Today
Yesterday
    뽀로로친구에디
    최근에 올라온 글