- Home /
Question by
AnimalStuffed · Jun 27, 2017 at 10:56 PM ·
joystickimplement
How to implement joystick?
Joystick will not implement and the game will pause everytime I try to move the joystick?
CODE:
using UnityEngine; using System.Collections;
using UnityEngine.EventSystems;
using UnityEngine.UI; using System;
public class VirtualJoystick : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler { public RectTransform thumb;
private Vector2 originalPosition;
private Vector2 originalThumbPosition;
void Start()
{
originalPosition = this.GetComponent<RectTransform>().localPosition;
originalThumbPosition = thumb.localPosition;
thumb.gameObject.SetActive(false);
delta = Vector2.zero;
}
public Vector2 delta;
void OnBeginDrag(PointerEventData eventData)
{
thumb.gameObject.SetActive(true);
Vector3 worldPoint = new Vector3();
RectTransformUtility.ScreenPointToWorldPointInRectangle(
this.transform as RectTransform,
eventData.position,
eventData.enterEventCamera,
out worldPoint);
this.GetComponent<RectTransform>().position = worldPoint;
thumb.localPosition = originalThumbPosition;
}
void OnMouseDrag (PointerEventData eventData)
{
Vector3 worldPoint = new Vector3();
RectTransformUtility.ScreenPointToWorldPointInRectangle(
this.transform as RectTransform,
eventData.position,
eventData.enterEventCamera,
out worldPoint);
thumb.position = new Vector3();
var size = GetComponent<RectTransform>().rect.size;
delta = thumb.localPosition;
delta.x /= size.x / 2.0f;
delta.y /= size.y / 2.0f;
delta.x = Mathf.Clamp(delta.x, -1.0f, 1.0f);
delta.y = Mathf.Clamp(delta.y, -1.0f, 1.0f);
}
void OnEndDrag (PointerEventData eventData)
{
this.GetComponent<RectTransform>().localPosition = originalPosition;
delta = Vector2.zero;
thumb.gameObject.SetActive(false);
}
public void OnDrag(PointerEventData eventData)
{
throw new NotImplementedException();
}
void IEndDragHandler.OnEndDrag(PointerEventData eventData)
{
throw new NotImplementedException();
}
void IBeginDragHandler.OnBeginDrag(PointerEventData eventData)
{
throw new NotImplementedException();
}
}
Comment
Your answer
Follow this Question
Related Questions
simple x-y joystick 0 Answers
How to make Lerpz Sidescroller work with iPhone Joystick? 1 Answer
Moving Joysticks 0 Answers
2 Player Joystick game 1 Answer
GetButton("Joy_button0") will not return true on startup. 0 Answers