Unity

[Unity] Chap03. 스크립트 작성하기

mooni_ 2024. 2. 26. 16:02

3-1. 스크립트로 게임 오브젝트 조작하기

유니티에서는 C#을 사용함

PlayerController라는 이름의 C# script 생성 후 컴포넌트 추가
Player Asset 폴더와 인스펙터 뷰에 스크립트가 존재하는 것을 볼 수 있음

 

[C# script 초기 코드]

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

public class PlayerController : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

 

 

 


3-2. C# 프로그래밍의 기초

자료형 변수 연산자 주석 메서드 인수 반환값 클래스 어쩌구

 

 


3-3. PlayerController 스크립트 살펴보기

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

public class PlayerController : MonoBehaviour
{
    Rigidbody2D rbody;
    float axisH = 0.0f;
    public float speed = 3.0f;

    // Start is called before the first frame update
    void Start()
    {
        // Rigidbody2D 가져오기
        rbody = this.GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        // 수평 방향의 입력 확인
        axisH = Input.GetAxisRaw("Horizontal");
        
        // 방향 조절
        if (axisH > 0.0f)
        {
            // 오른쪽 이동
            Debug.Log("오른쪽 이동");
            transform.localScale = new Vector2(1, 1);
        }
        else if(axisH < 0.0f)
        {
            // 왼쪽 이동
            Debug.Log("왼쪽 이동");
            transform.localScale = new Vector2(-1, 1);  // 좌우반전
        }
    }

    void FixedUpdate()
    {
        // 속도 갱신하기
        rbody.velocity = new Vector2(speed * axisH, rbody.velocity.y);
    }
}

 

→ Player가 이동하고 좌우반전이 되도록하는 코드를 따라 쳐봄

 

 

!! 근데 ground를 벗어나서 떨어질 때 끝도 없이 떨어지는 Player가 너무 불쌍했음

!! 그래서 Y좌표가 특정 값이 되면 초기 위치로 돌아오는 코드를 추가로 작성해봄

public class PlayerController : MonoBehaviour
{
    Rigidbody2D rbody;
    float axisH = 0.0f;
    public float speed = 3.0f;
    Vector2 resetPosition;    // 초기 포지션을 저장할 변수
    Vector2 currentPosition;    // 현재 포지션을 저장할 변수
    int fail = -10;    // 오브젝트 포지션의 Y축 값과 비교할 기준

    // Start is called before the first frame update
    void Start()
    {
        rbody = this.GetComponent<Rigidbody2D>();
        resetPosition = this.transform.position;    // 시작할 때 초기 포지션 저장
        Debug.Log(resetPosition);    // console에 초기 포지션 출력
    }

    // Update is called once per frame
    void Update()
    {
        axisH = Input.GetAxisRaw("Horizontal");
        currentPosition = transform.position;    // 프레임마다 현재 위치를 계속 업데이트

        if (axisH > 0.0f)
        {
            /*Debug.Log("오른쪽 이동");*/
            transform.localScale = new Vector2(1, 1);
        }
        else if(axisH < 0.0f)
        {
            /*Debug.Log("왼쪽 이동");*/
            transform.localScale = new Vector2(-1, 1);
        }

        // 현재 위치를 기준과 비교하여 바닥으로 떨어졌을 경우 처음 위치로 옮김
        if (currentPosition.y < fail)
        {
            Debug.Log(transform.position);  //옮겨지기 전 오브젝트의 위치
            transform.position = resetPosition;
        }
    }
}

→ 초기 위치랑 떨어졌을 때의 위치를 console에 log해봄

 

  원하는 대로 실행이 되었다!

(인스펙터 뷰에 변수들은 처음에 Public으로 선언했어서 표시되었다 후에 수정함)

 

 

!! 근데 이제 점프도 해보고 싶어졌음 그래서 책에 GetButtonDown을 참고하여 작성해봄

public class PlayerController : MonoBehaviour
{
    Rigidbody2D rbody;
    float axisH = 0.0f;
    public float speed = 3.0f;
    Vector2 resetPosition;
    Vector2 currentPosition;
    int fail = -10;
    bool jump;    // boolean 타입으로 변수 선언

    // Start is called before the first frame update
    void Start()
    {
        rbody = this.GetComponent<Rigidbody2D>();
        resetPosition = this.transform.position;  
        Debug.Log(resetPosition);  
    }

    // Update is called once per frame
    void Update()
    {
        axisH = Input.GetAxisRaw("Horizontal");
        currentPosition = transform.position;   
        jump = Input.GetButtonDown("Jump");    // 스페이스바가 눌렸는가에 대한 여부를 입력 받음

        if (axisH > 0.0f)
        {
            /*Debug.Log("오른쪽 이동");*/
            transform.localScale = new Vector2(1, 1);
        }
        else if(axisH < 0.0f)
        {
            /*Debug.Log("왼쪽 이동");*/
            transform.localScale = new Vector2(-1, 1);
        }

        if (currentPosition.y < fail)
        {
            Debug.Log(transform.position);
            transform.position = resetPosition;
        }

        // True 면 아래 코드 실행
        if (jump)
        {
            Debug.Log("Jump!!");
            transform.position = new Vector2(currentPosition.x, currentPosition.y + 0.5f);    // 현재 위치의 Y좌표를 0.5만큼 이동시킴
        }
    }
}

 

→ 사실 점프라고 하기에는 그냥 위에서 떨어트리는 형태지만... 스터디 첫번째주차니까

 

→ 실행 잘 됨!

 

 

!! 아래는 play 영상

 

 

 

*교재 : 누구나 할 수 있는 유니티 2D 게임 제작

 

 

↓ 약간 수정해봄!

 

[Unity] 1차 Study : 점프, 닉네임 달기 완성!

[Unity] Chap03. 스크립트 작성하기 3-1. 스크립트로 게임 오브젝트 조작하기 유니티에서는 C#을 사용함 PlayerController라는 이름의 C# script 생성 후 컴포넌트 추가 Player Asset 폴더와 인스펙터 뷰에 스크

mooni-123.tistory.com