[Memo-Unity] 3. ์กฐ์ด์คํฑ(JoyStick)
์นดํ ๊ณ ๋ฆฌ: MeMo Unity
ํ๊ทธ: MeMo Unity, Unity
์กฐ์ด์คํฑ(JoyStick)
๊ณ ๋ฐ์ฌ์ ์ ๋ํฐ ๊ธฐ์ด๋ฅผ ์ ๋ฆฌ.
Joystick
์ด๋ฏธ์ง
- ์กฐ์ด์คํฑ์ผ๋ก ์ฌ์ฉ ํ ์ด๋ฏธ์ง ์์ฑ ( UI- IMAGE)
- Canvas ์์ ํด์๋ ์ค์ ex) scale with screen size , 1600:1000 , 0.5
- ui ์ด๋ฏธ์ง ์ฌ์ด์ฆ ์กฐ์
- ์ปจํธ๋กค๋ฌ๋ก ์ฌ์ฉ๋ ์ด๋ฏธ์ง ์ถ๊ฐ , ๋ฐฐ๊ฒฝ์ ์์์ผ๋ก ์ค์
C์คํฌ๋ฆฝํธ
using.UnityEngine.EventSystems
1. MoveTouch.CS
์กฐ์ด์คํฑ ํฐ์น์ ๋ฐ์ํ๋ ์ด๋ฒคํธ
MoveTouch.cs
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class MoveTouch : MonoBehaviour, IPointerDownHandler, IDragHandler, IPointerUpHandler
{
private Image imageBackground;
private Image imageController;
private Vector2 TouchPosition;
private void Awake() {
imageBackground = GetComponent<Image>();
imageController = transform.GetChild(0).GetComponent<Image>();
}
//ํฐ์น์ 1ํ
public void OnPointerDown(PointerEventData eventData){
}
//ํฐ์นํ ๋๋๊ทธ ๋งคํ๋ ์
public void OnDrag(PointerEventData eventData){
TouchPosition = Vector2.zero;
// ์กฐ์ด์คํฑ์ ์์น๊ฐ ์ด๋์ ์๋ ๋์ผํ ๊ฐ์ ์ฐ์ฐํ๊ธฐ ์ํด
// touchPosition์ ์์น ๊ฐ์ ์ด๋ฏธ์ง์ ํ์ฌ ์์น๋ฅผ ๊ธฐ์ค์ผ๋ก ์ผ๋ง๋ ๋จ์ด์ ธ ์๋์ง์ ๋ฐ๋ผ ๋ค๋ฅด๊ฒ ๋์จ๋ค.
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(
imageBackground.rectTransform, eventData.position,eventData.pressEventCamera,out TouchPosition ))
{ //์ด๋ฏธ์ง์ teansform์ ๋ณด, ํ๋ฉดํฐ์น์ขํ, ํ์ฌ ํ๋ฉด์ ๋ํ ์นด๋ฉ๋ผ, ์ฐ์ฐ๋ ์ขํ๋ฅผ ์ ์ฅ
// touchposition๊ฐ ์ ๊ทํ ์ด๋ฏธ์ง ํฌ๊ธฐ๋ก ๋๋ [๊ฐ : 0~1 ]
// ๋ฐฐ๊ฒฝ๋ฐ์ผ๋ก ๋๊ฐ๋ฉด ์ด์์ ๊ฐ์ด ๋์จ๋ค -2 ~ 2
TouchPosition.x = (TouchPosition.x / imageBackground.rectTransform.sizeDelta.x);
TouchPosition.y = (TouchPosition.y / imageBackground.rectTransform.sizeDelta.y);
//normalized๋ฅผ ์ด์ฉํด ํฐ์น ์ขํ๊ฐ์ -1 ~ 1๋ก ์ ํ
TouchPosition = (TouchPosition.magnitude > 1) ? TouchPosition.normalized : TouchPosition;
// ์ปจํธ๋กค๋ฌ ์์ง์์ ์ ํ
imageController.rectTransform.anchoredPosition = new Vector2(
TouchPosition.x * imageBackground.rectTransform.sizeDelta.x/2,
TouchPosition.y * imageBackground.rectTransform.sizeDelta.y/2
);
}
}
//ํฐ์น์ข
๋ฃ์ 1ํ
public void OnPointerUp(PointerEventData eventData){
//์ข
๋ฃ์ ์์น,๋ฐฉํฅ ์ด๊ธฐํ
imageController.rectTransform.anchoredPosition =Vector2.zero;
TouchPosition = Vector2.zero;
}
public float Horizontal(){
return TouchPosition.x;
}
public float Vertical(){
return TouchPosition.y;
}
}
- OnPointerDown , OnDrag , OnPointerUp๋ฑ์ ํจ์๋ฅผ ์ฌ์ฉํ๊ธฐ ์ํด
- IPointerDownHandler, IDragHandler, IPointerUpHandler๋ฅผ ์ฌ์ฉ
- ์กฐ์ด์คํฑ์ผ๋ก ์ค๋ธ์ ํธ ์์ง์ด๊ธฐ.
2. Movement.CS
์กฐ์ด์คํฑ์ผ๋ก ์ธํด ์์ง์ด๋ ์ค๋ธ์ ํธ ์ฝ๋
Movement.cs
using UnityEngine;
public class Movement : MonoBehaviour
{
[SerializeField]
private MoveTouch movetouch;
private float movespeed = 10 ;
void Update()
{
float x = movetouch.Horizontal();
float y = movetouch.Vertical();
if (x!=0||y!=0)
{
transform.position += new Vector3(x,y,0)*movespeed*Time.deltaTime;
}
}
}
๋๊ธ๋จ๊ธฐ๊ธฐ