Хочу в игре такое управление как в Color Road - https://vk.com/video174341022_456239047
И я сделал это здесь ( через джойстик) - https://vk.com/video174341022_456239048
Разница в том, что в игре Color Road гамбургер можно держать в центре без всякого напряжения, это очень удобно от края экрана идти в центр. В моем управлении, чтобы держаться в центре экрана нужно приложить немало усилий, так как если нажать джойстик чуть левее, то треугольник улетает к краю экрана, а если не отпускать джойстик идите влево, он будет двигаться со скоростью черепахи.
Мой код джойстика:
Код: Выделить всё
public class VirtualJoystick : MonoBehaviour, IDragHandler, IPointerUpHandler, IPointerDownHandler {
private Image backgroundImage;
private Image joystickImage;
private Vector3 inputVector;
private void Start()
{
backgroundImage = GetComponent();
joystickImage = transform.GetChild(0).GetComponent();
}
public virtual void OnDrag(PointerEventData eventData)
{
Vector2 pos;
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(backgroundImage.rectTransform, eventData.position,
eventData.pressEventCamera, out pos))
{
pos.x = (pos.x / (backgroundImage.rectTransform.sizeDelta.x));
//pos.y = (pos.y / backgroundImage.rectTransform.sizeDelta.y);
inputVector = new Vector3(pos.x * 2f, 0, 0);
inputVector = (inputVector.magnitude > 1.0f) ? inputVector.normalized : inputVector;
joystickImage.rectTransform.anchoredPosition = new Vector3(inputVector.x * (backgroundImage.rectTransform.sizeDelta.x / 2),
inputVector.z * inputVector.y);
}
}
public virtual void OnPointerDown(PointerEventData eventData)
{
OnDrag(eventData);
}
public virtual void OnPointerUp(PointerEventData eventData)
{
inputVector = Vector3.zero;
joystickImage.rectTransform.anchoredPosition = Vector3.zero;
}
public float Horizontal()
{
if (inputVector.x != 0)
{
return inputVector.x;
}
else
{
return Input.GetAxis("Horizontal");
}
}
}
Код: Выделить всё
public class PlayerMover : MonoBehaviour {
public VirtualJoystick joystick;
private Vector3 MoveVector;
private Rigidbody2D rigidbody;
public float moveSpeed = 10;
void Start()
{
rigidbody = gameObject.GetComponent();
}
void Update()
{
MoveVector = PoolInput();
Move();
}
private void Move()
{
rigidbody.velocity = Vector2.zero;
rigidbody.velocity = ((MoveVector * moveSpeed));
}
private Vector3 PoolInput()
{
Vector3 dir = Vector3.zero;
dir.x = joystick.Horizontal();
dir.y = 0;
dir.z = 0;
if (dir.magnitude > 1)
dir.Normalize();
Debug.Log("Dir = " + dir);
return dir;
}
}
P.S Извините за мой плохой английский
Подробнее здесь: https://stackoverflow.com/questions/513 ... h-joystick
Мобильная версия