Notice
Recent Posts
Recent Comments
Link
«   2025/06   »
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
Archives
Today
Total
관리 메뉴

행복한 개구리

Unity 3D 개인프로젝트 21.04.18. 본문

Unity/Project : Unity 3D Untitled

Unity 3D 개인프로젝트 21.04.18.

HappyFrog 2021. 4. 20. 23:49

조이스틱을 구현했다. 플레이어의 움직임과 결합은 아직 안했지만, 인터페이스와 패널을 이용하여 화면 어디를 클릭해도 조이스틱이 구현될 수 있도록 했다. 또, 드래그가 끝나면 사라지도록 했다.

 

버튼이 원 밖으로 나가는 것이 거슬린다.

 

그래서 막아보았다.

RectTransform으로 배경원의 반지름을 구한 뒤, 반지름보다 멀어지면 반지름위치에서 멈추도록 코드를 짰다.

 

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

public class JoyStickController : MonoBehaviour, IDragHandler, IPointerDownHandler, IPointerUpHandler
{
    public GameObject back;
    public GameObject handle;


    RectTransform rectBack;
    RectTransform rectHandle;
    Vector3 axis;
    Vector3 startPos;
    float radius;
    bool isOn = false;
    



    private void Awake()
    {

        this.rectBack = this.back.GetComponent<RectTransform>();
        this.radius = this.rectBack.rect.width * 0.5f;
    }

    void Start()
    {

    }
       

    void Update()
    {
        Debug.Log(this.isOn);
        Debug.Log(this.radius);
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        this.back.SetActive(true);
        if (!this.isOn)
        {
            this.isOn = true;
            this.back.transform.position = eventData.position;
            this.startPos = this.back.transform.position;
            this.handle.transform.position = eventData.position;
            Debug.Log("PointerDown");
        }



    }


    public void OnDrag(PointerEventData eventData)
    {
        this.handle.transform.position = Input.mousePosition;
        Vector3 handleVec = ((Vector3)eventData.position - this.startPos).normalized;

        float distance = Vector3.Distance((Vector3)eventData.position, this.startPos);
        if (distance < this.radius)
        {
            this.handle.transform.position = this.startPos + handleVec * distance;
        }
        else
        {
            this.handle.transform.position = this.startPos + handleVec * this.radius;
        }
        Debug.Log("Drag");

    }



    public void OnPointerUp(PointerEventData eventData)
    {
        this.back.SetActive(false);
        this.isOn = false;
        this.handle.transform.position = this.startPos;
        Debug.Log("PointerUp");

    }
}

++if (eventData.position.x < 960) 를 PointerDown 최상위 조건문으로 추가하여 만약 클릭위치가 맵의 좌측절반을 벗어나면 조이스틱이 생성되지 않게 했다.

============================================================================

**주의하자.

Apply Root Motion을 체크해뒀더니 Gravity를 켜두면 캐릭터가 하늘로 떠오르고 좌표는(Position) 가만히 있어도 요동쳤으며 조이스틱을 돌려도 움직이지 않았다. 상황에 맞게 사용하자.

 

++ 조이스틱을 움직이고 있을때는 정상적으로 작동하는데 커서를 멈추는 순간 캐릭터의 움직임도 멈추는 현상 발견.