본문 바로가기
Unity/코인먹기 게임

[유니티] 캐릭터가 화면을 넘어가지 않도록 만들기

by Skull Crusher 2021. 4. 25.
728x90
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Movement : MonoBehaviour
{
    // 현재 캐릭터의 Transform 컴포넌트 참조
    public Transform trans;

    public float speed;

    // Start is called before the first frame update
    void Start()
    {
        // 캐릭터의 위치 x:0, y:2, z:0 으로 설정
        // trans.position = new Vector3(0f, 2f, 0f);
    }

    // Update is called once per frame
    void Update()
    {
        // Input.GetAxisRaw를 이용해 좌우 방향키값을 전달 받음
        // 좌 : -1, 우 : 1, 누르지않음 : 0
        float h = Input.GetAxisRaw("Horizontal");

        // Input.GetAxisRaw를 이용해 상하 방향키값을 전달 받음
        // 하 : -1, 상 : 1, 누르지않음 : 0
        float v = Input.GetAxisRaw("Vertical");

        //Debug.Log("좌우 이동 값 : " + h + ", 상하 이동 값 : " + v);

        // 방향 벡터 생성
        // 오른쪽 -> 1, 0, 0
        // 왼쪽 -> -1, 0, 0
        // 위쪽 -> 0, 1, 0

        // 방향 객체 생성(구조체)
        Vector3 direction;
        direction.x = h;
        direction.y = v;
        direction.z = 0;

        Debug.Log("캐릭터 위치 : " + trans.position);
        Debug.Log("캐릭터 위치 x : " + trans.position.x + ", y : " + trans.position.y);

        Vector3 transaction = direction * speed * Time.deltaTime;

        // 이동 공식
        // Transform.Translate(방향 * 속도 * Time.deltaTime);
        // -> Tranform 객체의 참조변수인 trans를 통해 Tranlate메소드(유형2)를 실행함
        //      Translate메소드의 요구 매개변수값은 Vector값이다.
        trans.Translate(transaction);

        // 왼쪽/오른쪽 경계 좌표 x : 3.4, 1.2
        // 위쪽/아래쪽 경계 좌표 y : 4.3

        // 캐릭터가 왼쪽/오른쪽 경계를 넘었을 경우
        if (trans.position.x < -3.4f)
        {
            // 캐릭터의 위치를 경계값으로 설정
            trans.position = new Vector3(-3.4f, trans.position.y, 0f);
        }
        else if (trans.position.x > 1.2f)
        {
            trans.position = new Vector3(1.2f, trans.position.y, 0f);
        }

        if (trans.position.y < -4.3f)
        {
            // 캐릭터의 위치를 경계값으로 설정
            trans.position = new Vector3(trans.position.x, -4.3f, 0f);
        }
        else if (trans.position.y > 4.3f)
        {
            trans.position = new Vector3(trans.position.x, 4.3f, 0f);
        }


    }
}

 

댓글