unity - 일정 수치씩 마우스 드래그로 값 변환하기 handle range value when i Input mouse drag.

1. 설정


2. C#코드

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
 
public class test : MonoBehaviour {
    
    Vector3 firstPosition; // 처음 위치 저장
    public Text _textValue; // 텍스트
 
    float value = 0// 실제로 들어가는 값.
    float fixedValue = 0// 처음찍었을때 고정값.
    int firstValue = 0// 처음 위치값
    int lastValue = 0// 마우스의 움직임에 따라 달라지는 마지막 값.
    bool inputMouseCheck = false;
 
    // Update is called once per frame
    void Update()
    {
        // 마우스 버튼 누를 때
        if (Input.GetMouseButtonDown(0)) 
        {
            // 3D raycast
            RaycastHit hit = new RaycastHit();
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
 
            if (Physics.Raycast(ray.origin, ray.direction, out hit))
            {
                // 만약 누른곳의 collider.tag 가 Range 일때
                if (hit.collider.tag == "Range")
                {
                    firstPosition = Input.mousePosition;            // 처음 위치vector 저장
                    firstValue = CountingRange(firstPosition.y);    // 처음 위치 값을 저장
                    fixedValue = value;                             // 기존 value에 저장되어 있는 값을 저장
                    inputMouseCheck = true
                }
            }
        }
        // 마우스 버튼을 땔 때
        else if (Input.GetMouseButtonUp(0))
        {
            inputMouseCheck = false;
        }
        // 만약 inputMouseCheck == true
        if (inputMouseCheck) Value(); 
    }
    
    public void Value()
    {
        Vector3 lastPosition = Input.mousePosition; // 마지막 위치vector 저장
 
        // 이 범위를 벗어나면 inputMoseCheck false가 되서 마우스 버튼 땔때와 같은 효과가 난다.
        // 범위는 Debug.Log(Input.mousePosition)으로 알수 있다.
        if (Input.mousePosition.y > 290 || Input.mousePosition.y < 190 || Input.mousePosition.x < 350 || Input.mousePosition.x > 450) inputMouseCheck = false;
 
        lastValue = CountingRange(lastPosition.y); // 마지막 위치 값을 저장
 
        value = lastValue - firstValue + fixedValue; // 값 = 마지막값 - 처음값 + 기존값
        
        if (value >= 30) value = 30// 최대값 설정(실제로 보여지는 최대값 *0.5가 됨.) 
        else if (value <= -30) value = -30// 최소값 설정(이하동문)
        _textValue.text = (value * 0.5f).ToString(); // text에 값* 원하는 수치만큼 시킴.
        
    }
    
    // 클릭범위 카운팅
    int CountingRange(float point)
    {
        int result = 0;
        int count = 0;
        while (true)
        {
            result = (10 * count) + 190;
            count++;
            if (result > point) break;
        }
 
        return count;
    }
}
 
cs

3. 실행결과

댓글