포트폴리오

유니티 기록

자동산양 2023. 1. 18. 01:26

예전에 급하게 만들었던 게임을 수정시켜서 발전시키고 싶어서 켰는데

 

예전 코드 알아보는데만 하루 넘게걸렸다 그래도 다행인게 시간은 걸려도 발전은 된다는 점

 

그래서 하나하나씩 기능을 추가하기로 하고 우선 우측 버튼의 기능을 넣기로 하였다

 

우선 버튼에 사용한 스크립트(ButtonScript)

using UnityEngine.UI;

public class ButtonScript : MonoBehaviour
{
    // Start is called before the first frame update
    GameObject Player; // Player태그를 가진 게임오브젝트를 불러옴
    PlayerCTR playerCTR; // PlayerCTR의 클래스를 불러옴


    void Start()
    {
        Player = this.gameObject; // 일단 플레이어 태그 붇은 오브젝트 찾아야하고
        playerCTR = Player.GetComponent(); // 게임오브젝트 함수 가져옴

    }
    

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

    }

    public void LeftbtnDown()
    {
        playerCTR.Lfmove = false;
        Debug.Log("눌렀다고");
        Debug.Log(playerCTR.Lfmove); 
    }

    public void LeftbtnUp()
    {
        playerCTR.Lfmove = true;
        Debug.Log("뗏다고");
        Debug.Log(playerCTR.Lfmove);
    }

    public void rfftbtnDown()
    {
        playerCTR.Rfmove = false;
        Debug.Log("눌렀다고");
        Debug.Log(playerCTR.Lfmove);
    }

    public void rfftbtnUp()
    {
        playerCTR.Rfmove = true;
        Debug.Log("뗏다고");
        Debug.Log(playerCTR.Lfmove);
    }


    void Awake()
    {
        
    }

}

위에 스크립트중 쓸모없는게 있지만 훗날 써먹을거같아서 일단 놔뒀다

 

그리고 Player 태그에 달린 캐릭터를 움직이기 위한 스크립트

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;


public class PlayerCTR : MonoBehaviour
{
    //임시추가
    Rigidbody2D rigid2d;
    Animator animator;
    public bool Lfmove = false;
    public bool Rfmove = false;
    Vector3 moveVelocity = Vector3.zero;
    public float moveSpeed=1f;

    //임시추가

    public AudioClip audioScore;
    AudioSource audioSource;

    int count=0;

    // Start is called before the first frame update    
    void Start()
    {
       animator = gameObject.GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        if (Lfmove)
        {
            animator.SetBool("Direction", false);
            moveVelocity = new Vector3(0,20f,0);
            transform.position += moveVelocity * moveSpeed * Time.deltaTime;            
            
        }
        if(Rfmove)
        {
            animator.SetBool("Direction", true);
            moveVelocity = new Vector3(0,-1f, 0);
            transform.position += moveVelocity * moveSpeed * Time.deltaTime;
        }

    }
    public float speed;
    private Joystick joystick;

    private ButtonScript buttonScript; // 버튼 작동 실험 중

    void Awake()
    {
        joystick = GameObject.FindObjectOfType<Joystick>();
        this.audioSource = GetComponent<AudioSource>();
        
    }

    void FixedUpdate()
    {
        if (joystick.Horizontal != 0 || joystick.Vertical != 0)
        {
            MoveControl();
        }

        
    }
    

    private void MoveControl()
    {
        Vector3 upMovement = Vector3.up * speed * Time.deltaTime * joystick.Vertical;
        Vector3 rightMovement = Vector3.right * speed * Time.deltaTime * joystick.Horizontal;
        transform.position += upMovement;
        transform.position += rightMovement;        

    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.CompareTag("Finish1"))
        {
            Debug.Log("골인입니다");
            SceneManager.LoadScene("NextStage1_2");
            count = 0; // 골인시 스코어 초기화
        }

        else if (other.gameObject.CompareTag("Finish2"))
        {
            Debug.Log("골인입니다");
            SceneManager.LoadScene("NextStage2_3");
            count = 0; // 골인시 스코어 초기화
        }

        else if (other.gameObject.CompareTag("Finish3"))
        {
            Debug.Log("골인입니다");
            SceneManager.LoadScene("NextStage3_4");
            count = 0; // 골인시 스코어 초기화
        }

        else if (other.gameObject.CompareTag("Finish4"))
        {
            Debug.Log("골인입니다");
            SceneManager.LoadScene("NextStage4_5");
            count = 0; // 골인시 스코어 초기화
        }



        else if (other.gameObject.CompareTag("AddScore"))
        {
            count = count + 1;
            Debug.Log("스코어" + count + "점");
            audioSource.clip = audioScore;
            audioSource.Play();
            other.gameObject.SetActive(false);            
        }

    }

}

일단

1. 캐릭터 움직임을 조이스틱에 받아서 움직이게 하는거

 

2. 스코어 오브젝트 먹었을 경우 스코어 1점씩 오르게

 

3. Player 골인 지점 도달 시 다음 스테이지

 

4. 우측 하단 버튼을 눌렀을 경우 점프(추후 변경이나 추가 가능하게)

 

4번이 며칠동안 걸려서 매우 고생했다

 

우선

void Start()
    {
        Player = this.gameObject; // 일단 플레이어 태그 붇은 오브젝트 찾아야하고
        playerCTR = Player.GetComponent(); // 게임오브젝트 함수 가져옴

    }

여기에서 플레이어 태그 오브젝트 가져오는 함수를 사용할줄 몰라서 쩔쩔맸다

 

그리고 아래의 playerCTR 클래스는 원래 클래스명이 달랐는데 다른 태그명이랑 겹쳐서 헛갈려서 바꿨다

 

클래스나 변수명 정할때는 겹치지 않게 대소문자 구분 잘 하여 쓰도록 하자

 

그리고 움직임에서 막혔는데

  // Update is called once per frame
    void Update()
    {
        if (Lfmove)
        {
            animator.SetBool("Direction", false);
            moveVelocity = new Vector3(0,20f,0);
            transform.position += moveVelocity * moveSpeed * Time.deltaTime;            
            
        }
        if(Rfmove)
        {
            animator.SetBool("Direction", true);
            moveVelocity = new Vector3(0,-1f, 0);
            transform.position += moveVelocity * moveSpeed * Time.deltaTime;
        }

    }

예전 만들어둔 트랜스폼 함수를 이용하면 쉽게 이동시킬수 있겠지 하다가

 

버튼을 한번 누르면 무조건 특정 위치로 되돌아가는 바람에 무엇이 잘못됐나 한참고민했다가

 

transform.position = moveVelocity * moveSpeed * Time.deltaTime;

 

이부분이 잘못됐다는걸 깨달았다

 

저런식으로 식을 써버리면 그냥 포지션 값에 저 *값이 그냥 들어가버린다

 

그래서 =를 +=로 수정해줘서 1번 사이클 돌릴때마다 저 값이 계속해서 더해지도록 바꿨더니 잘 움직여줬다

 

모바일 환경에서 돌아가도록 조이스틱과 버튼을 구현한것이라 컴퓨터로는 움직이면서 점프가 힘들다

그리고 아직 점프에 대해 해결해야 될 방안은 연속점프 안되기 점프 좀더 매끄럽게 다듬기 등을 해야할 것 같다

 

+ 추가

 

gravity 값을 0으로 할때는 이동에 문제가 전혀 없었는데 gravity 적용 이후 콜라이더 충돌떄문에 이동이 매끄럽지 못한

 

문제가 발생하여 충돌 문제부터 다시 설계해야 할 것 같다

'포트폴리오' 카테고리의 다른 글

자기소개서 수정하기  (4) 2025.03.01
포트폴리오 묶음  (0) 2024.02.28
VBA기초부터(1)  (0) 2024.01.16
유니티 기록  (0) 2022.12.27
테이블 관리 실무  (0) 2021.12.05