7교시 탐정

2023. 6. 22. 14:36유니티 엔진

영상

 

작업기간 12주, 개발인원 4명,  기획 및 프로그래밍 담당

 

'7교시 탐정'은 횡스크롤 추리게임으로 플레이어는 학교에서 일어난 도난사건을 해결해야합니다.

조작법 - AD(이동), F(상호작용), E(상호작용)

 

 

인벤토리 아이템 스크립트

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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Naninovel;
 
public class InventoryItem : MonoBehaviour
{
    private Image imageComponent; //이미지 컴포넌트를 참조하는 변수
    private ICustomVariableManager variableManager; // 변수 매니저를 참조하는 변수
    public string thisIconName; // 아이콘의 이름을 저장하는 변수
    private GameObject newObj; // new 텍스트프리팹
    private bool isImageChanged = false;  // 이미지가 변경되었는지를 표시하는 변수
 
    void Start()
    {
        //초기화
        variableManager = Engine.GetService<ICustomVariableManager>();
        variableManager.OnVariableUpdated += OnVariableUpdated;
 
        imageComponent = GetComponent<Image>();
 
        // Resources 폴더에서 newObj 프리팹을 로드하고 인스턴스를 생성
        GameObject newObjPrefab = Resources.Load<GameObject>("newObj");
        newObj = Instantiate(newObjPrefab, transform);
 
        // newObj의 위치를 현재 오브젝트의 오른쪽 위로 이동
        RectTransform rectTransform = newObj.GetComponent<RectTransform>();
        rectTransform.anchorMin = new Vector2(11);
        rectTransform.anchorMax = new Vector2(11);
        rectTransform.anchoredPosition = new Vector2(00);
 
 
        if (newObj != null)
        {
            // newObj 비활성화
            newObj.SetActive(false);
        }
 
        UpdateSprites();
    }
 
    void OnDestroy() // 게임 오브젝트가 파괴될 때 이벤트를 해제
    {
        if (variableManager != null)
        {
            variableManager.OnVariableUpdated -= OnVariableUpdated;
        }
    }
 
    private void OnVariableUpdated(CustomVariableUpdatedArgs args) // 변수 업데이트 이벤트에 대한 처리를 정의
    {
        UpdateSprites();
    }
 
    private void UpdateSprites() // 스프라이트를 업데이트하는 메서드
    {
        bool shouldChange;
        variableManager.TryGetVariableValue<bool>(thisIconName, out shouldChange);
 
        if (shouldChange)
        {
            ChangeImage(thisIconName + "Icon");
 
        }
    }
 
    public void ChangeImage(string iconName) // 이미지를 변경하는 메서드
    {
        if (iconName == null || iconName == string.Empty)
        {
            if (imageComponent != null)
            {
                imageComponent.sprite = null;
            }
            return;
        }
 
        if (imageComponent == null)
        {
            Debug.LogWarning("Image component is missing on the game object.");
            return;
        }
        // Resources 폴더에서 스프라이트를 로드하고 이미지 컴포넌트에 할당
        imageComponent.sprite = Resources.Load<Sprite>(iconName);
 
        if(newObj != null)
        {
            newObj.SetActive(true); // 아이템이 변경될 때 newObj를 활성화
            isImageChanged = true// 이미지가 변경되었음을 표시
        }
    }
 
    public void OnButtonClick()
    {
        if (newObj != null && isImageChanged)
        {
            Destroy(newObj); // newObj를 파괴
            isImageChanged = false// 이미지 변경 상태를 초기화
        }
    }
}
 
 
cs

 

파이널 추리 선 긋기 퍼즐 스크립트

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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Linq;
using UnityEngine.SceneManagement;
using Naninovel;
 
public class WireTask_T : MonoBehaviour
{
    public List<Button> buttons; // 버튼 리스트
    public Image wire; // 전선 이미지
    public Image[] connectedWires; // 연결된 전선들 배열
    private bool isDragging; // 드래그 중인지 여부
    private int currentButtonIndex; // 현재 선택된 버튼 인덱스
    private int connectedButtonIndex; // 연결된 버튼 인덱스
    private bool isConnected; // 버튼이 연결되었는지 여부
    private RectTransform wireRectTransform; // 전선의 RectTransform 컴포넌트
    float buttonHoldDuration = 0.1f; // 버튼을 누르고 있어야 하는 시간
    float buttonHoldTimer; // 버튼을 누르고 있는 타이머
    public GameObject wireParent; // 전선 부모 객체
    public Canvas canvas; // 캔버스 객체
    private int[] correctWires = { 3561011 }; // 정답 전선 인덱스 배열
 
    private ICustomVariableManager variableManager; // 변수 매니저를 참조하는 변수
 
    public PlayScript playScript; // 재생 스크립트 객체
    public PlayScript playScript2; // 재생 스크립트2 객체
 
    public void DeactivateAllConnectedWires()
    {
        for (int i = 0; i < connectedWires.Length; i++)
        {
            connectedWires[i].gameObject.SetActive(false); // 모든 연결된 전선 비활성화
        }
    }
    public void CheckCorrectWiresConnected()
    {
        bool isCorrect = true;
        for (int i = 0; i < correctWires.Length; i++)
        {
            if (!connectedWires[correctWires[i]].gameObject.activeInHierarchy)
            {
                isCorrect = false;
                break;
            }
        }
        if (isCorrect)
        {
            Debug.Log("성공");
            playScript.Play(); // 정답일 경우 재생 스크립트 실행
        }
        else
        {
            Debug.Log("실패");
            playScript2.Play(); // 실패일 경우 재생 스크립트2 실행
        }
    }
    private Dictionary<(intint), int> connectionMapping = new Dictionary<(intint), int>
    {
        // 버튼 연결에 대한 매핑 정보
        {(02), 0},
        {(03), 3},
        {(04), 1},
        {(05), 2},
        {(12), 4},
        {(13), 8},
        {(14), 11},
        {(15), 13},
        {(2,0), 0},
        {(2,1), 4},
        {(2,3), 7},
        {(2,4), 5},
        {(2,5), 6},
        {(3,0), 1},
        {(3,1), 8},
        {(3,2), 7},
        {(3,4), 9},
        {(3,5), 10},
        {(4,0), 1},
        {(4,1), 11},
        {(4,2), 5},
        {(4,3), 9},
        {(4,5), 12},
        {(5,0), 2},
        {(5,1), 13},
        {(5,2), 6},
        {(5,3), 10},
        {(5,4), 12},
    };
 
    void Start()
    {
        // 변수 매니저를 가져옴
        variableManager = Engine.GetService<ICustomVariableManager>();
        wire.gameObject.SetActive(false); // 전선 비활성화
        wireRectTransform = wire.GetComponent<RectTransform>(); // 전선의 RectTransform 컴포넌트 가져옴
        wire.transform.SetParent(wireParent.transform, false); // 전선 부모 객체로 설정
    }
 
    void Update()
    {
        if (!isDragging)
        {
            for (int i = 0; i < buttons.Count; i++)
            {
                if (IsPointerOverButton(buttons[i].gameObject))
                {
                    if (Input.GetMouseButtonDown(0))
                    {
                        currentButtonIndex = i; // 현재 선택된 버튼 인덱스 설정
                        buttonHoldTimer = 0f;
                    }
                    if (Input.GetMouseButton(0&& i == currentButtonIndex)
                    {
                        buttonHoldTimer += Time.deltaTime;
                        if (buttonHoldTimer >= buttonHoldDuration)
                        {
                            StartDragging(i);
                        }
                    }
                }
            }
        }
 
        if (Input.GetMouseButton(0&& isDragging)
        {
            DragWire();
 
            isConnected = false;
            for (int i = 0; i < buttons.Count; i++)
            {
                if (i != currentButtonIndex && IsPointerOverButton(buttons[i].gameObject))
                {
                    connectedButtonIndex = i;
                    isConnected = true;
                    break;
                }
            }
            UpdateWire(connectedButtonIndex, isConnected);
        }
        else
        {
            if (!isConnected)
            {
                isDragging = false;
                wire.gameObject.SetActive(false);
            }
        }
 
        if (isConnected && Input.GetMouseButtonUp(0))
        {
            HandleConnection(connectedButtonIndex);
            isConnected = false;
        }
    }
 
    void StartDragging(int buttonIndex)
    {
        isDragging = true;
        currentButtonIndex = buttonIndex;
        wire.transform.position = buttons[buttonIndex].transform.position;
    }
 
    void DragWire()
    {
        wire.gameObject.SetActive(true);
        Vector3 buttonWorldPosition = buttons[currentButtonIndex].GetComponent<RectTransform>().TransformPoint(buttons[currentButtonIndex].transform.position);
        Vector3 mouseWorldPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        Vector2 direction = ((Vector2)mouseWorldPosition - (Vector2)wireParent.transform.position).normalized;
        float distance = Vector2.Distance(wireParent.transform.position, mouseWorldPosition);
        wireRectTransform.sizeDelta = new Vector2(distance, wireRectTransform.sizeDelta.y);
        wireRectTransform.anchoredPosition = Vector2.zero;
        wire.transform.localRotation = Quaternion.FromToRotation(Vector3.right, direction);
    }
 
    bool IsPointerOverButton(GameObject buttonGameObject)
    {
        PointerEventData eventData = new PointerEventData(EventSystem.current);
        eventData.position = Input.mousePosition;
        List<RaycastResult> results = new List<RaycastResult>();
        EventSystem.current.RaycastAll(eventData, results);
        return results.Exists(result => result.gameObject == buttonGameObject);
    }
 
    void UpdateWire(int targetButtonIndex, bool updateEndPosition)
    {
        wire.gameObject.SetActive(true);
        Vector2 button1Position = buttons[currentButtonIndex].transform.position;
        Vector2 button2Position;
        if (updateEndPosition)
        {
            button2Position = buttons[targetButtonIndex].transform.position;
        }
        else
        {
            button2Position = Input.mousePosition;
        }
        Vector2 direction = (button2Position - button1Position).normalized;
        float distance = Vector2.Distance(button1Position, button2Position);
        wireRectTransform.sizeDelta = new Vector2(distance, wireRectTransform.sizeDelta.y);
        wire.transform.position = button1Position + direction * distance * 0.5f;
        wire.transform.rotation = Quaternion.FromToRotation(Vector3.right, direction);
    }
 
    private Dictionary<intList<int>> buttonConnections = new Dictionary<intList<int>>();
 
    void HandleConnection(int targetButtonIndex)
    {
        int currentKey = currentButtonIndex;
        int targetKey = targetButtonIndex;
        if (connectionMapping.ContainsKey((currentKey, targetKey)))
        {
            int connectedWireIndex = connectionMapping[(currentKey, targetKey)];
            if (connectedWireIndex < 0 || connectedWireIndex >= connectedWires.Length)
            {
                Debug.LogError("Invalid connected wire index: " + connectedWireIndex);
                return;
            }
 
            if (!buttonConnections.ContainsKey(currentKey))
            {
                buttonConnections[currentKey] = new List<int>();
            }
            if (!buttonConnections.ContainsKey(targetKey))
            {
                buttonConnections[targetKey] = new List<int>();
            }
 
            if (((currentKey == 0 || targetKey == 0&& buttonConnections[0].Count == 1))
            {
                int buttonToClear = (currentKey == 0 || currentKey == 7) ? currentKey : targetKey;
                int existingConnectionIndex = buttonConnections[buttonToClear][0];
                connectedWires[existingConnectionIndex].gameObject.SetActive(false);
                buttonConnections[buttonToClear].RemoveAt(0);
                int oppositeButton = connectionMapping.FirstOrDefault(pair => pair.Value == existingConnectionIndex).Key.Item1;
                if (oppositeButton == buttonToClear)
                {
                    oppositeButton = connectionMapping.FirstOrDefault(pair => pair.Value == existingConnectionIndex).Key.Item2;
                }
                buttonConnections[oppositeButton].Remove(existingConnectionIndex);
            }
 
            if ((currentKey >= 2 && currentKey <= 5 && buttonConnections[currentKey].Count >= 2||
                (targetKey >= 2 && targetKey <= 5 && buttonConnections[targetKey].Count >= 2))
            {
                int buttonToDisconnect = (buttonConnections[currentKey].Count >= 2) ? currentKey : targetKey;
                int oldestConnectionIndex = buttonConnections[buttonToDisconnect][0];
                connectedWires[oldestConnectionIndex].gameObject.SetActive(false);
                buttonConnections[buttonToDisconnect].RemoveAt(0);
                int oppositeButton = connectionMapping.FirstOrDefault(pair => pair.Value == oldestConnectionIndex).Key.Item1;
                if (oppositeButton == buttonToDisconnect)
                {
                    oppositeButton = connectionMapping.FirstOrDefault(pair => pair.Value == oldestConnectionIndex).Key.Item2;
                }
                buttonConnections[oppositeButton].Remove(oldestConnectionIndex);
            }
 
            connectedWires[connectedWireIndex].gameObject.SetActive(true);
            buttonConnections[currentKey].Add(connectedWireIndex);
            buttonConnections[targetKey].Add(connectedWireIndex);
            isDragging = false;
        }
    }
}
 
cs

'유니티 엔진' 카테고리의 다른 글

Midway  (0) 2023.06.22
Human Disaster  (0) 2023.06.22
YSG (YeonSung Gallery)  (0) 2023.05.19
Help! MiniGame!  (0) 2023.04.28
Tank Battle!  (0) 2023.04.28