0
\$\begingroup\$

What I want to do is

  1. Pass a parameter called joystick_tag. (like this: Get3DJoystickPosition(joystick_tag))
  2. Get the current joystick.Horizontal, joystick.Vertical, Camera.main so that I can calculate the value shown in the following code snipped:
Camera.main.ScreenToWorldPoint(new Vector3((joystick.Horizontal + 1) * Screen.width / 2, (joystick.Vertical + 1) * Screen.height / 2, Camera.main.nearClipPlane));
  1. return that value.

It seems quite simple but in my code the joystick.Horizontal and the joystick.Vertical values are always 0 even if I move the joystick.

Basically, the method gets a string input, called joystick_tag. Then by the tag, every time the method gets called, it finds a joystick tagged by the tag. Then it calls the Update() method so that I can get the current joystick.Horizontal and joystick.Vertical.

This is the full code. The joystick class is from the Joystick Pack by Fenerax studios.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Korselo.JoyPos
{
    public class JoyPos : MonoBehaviour
    {
        public Joystick joystick;
        public Vector3 world_v;
        public string joystick_tag_public;
        // Start is called before the first frame update
        void Start()
        {
          
        }

        // Update is called once per frame
        void Update()
        {
            world_v = Camera.main.ScreenToWorldPoint(new Vector3((joystick.Horizontal + 1) * Screen.width / 2, (joystick.Vertical + 1) * Screen.height / 2, Camera.main.nearClipPlane));

            Debug.Log(world_v);
        }

        public Vector3 Get3DJoystickPosition(string joystick_tag)
        {
            GameObject joystickGameObject = GameObject.FindGameObjectWithTag(joystick_tag);
            if (joystickGameObject != null)
            {
                joystick = joystickGameObject.GetComponent<Joystick>();
            }
            Update();
            return world_v;
        }
    }
}
using UnityEngine;
using System.Linq;
using Werewolf.StatusIndicators.Services;
using System.Collections;
using Korselo.JoyPos;

namespace Werewolf.StatusIndicators.Components {
    public class LineMissile : SpellIndicator {

        // Fields

        private float arrowHeadScale;
        private Projector arrowHeadProjector;

        public GameObject ArrowHead;

        public float MinimumRange;

        public string joystick_tag;
        
        // Properties

        public override ScalingType Scaling { get { return ScalingType.LengthOnly; } }

        // Methods

        public override void Initialize() {
            base.Initialize();
            arrowHeadProjector = ArrowHead.GetComponent<Projector>();
            arrowHeadScale = arrowHeadProjector.orthographicSize;
        }

        public override void Update() {
            JoyPos joyPos = gameObject.AddComponent<JoyPos>();
            if (Manager != null) {
                Vector3 v = FlattenVector(joyPos.Get3DJoystickPosition(joystick_tag)) - Manager.transform.position;
                if(v != Vector3.zero) {
                    Manager.transform.rotation = Quaternion.LookRotation(v);
                }
                Scale = Mathf.Clamp((joyPos.Get3DJoystickPosition(joystick_tag) - Manager.transform.position).magnitude, MinimumRange, Range - ArrowHeadDistance()) * 2;
                ArrowHead.transform.localPosition = new Vector3(0, (Scale * 0.5f) + ArrowHeadDistance() - 0.12f, 0);
            }
        }

        public override void OnValueChanged() {
            base.OnValueChanged();
            arrowHeadProjector.aspectRatio = 1f;
            arrowHeadProjector.orthographicSize = arrowHeadScale;
        }

        /// <summary>
        /// Calculate distance of the Arrow Head from the centre point when scaling.
        /// </summary>
        private float ArrowHeadDistance() {
            return (float)arrowHeadProjector.orthographicSize * 0.96f;
        }
    }
}

--> LineMissile.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class Joystick : MonoBehaviour, IPointerDownHandler, IDragHandler, IPointerUpHandler
{
    public float Horizontal { get { return (snapX) ? SnapFloat(input.x, AxisOptions.Horizontal) : input.x; } }
    public float Vertical { get { return (snapY) ? SnapFloat(input.y, AxisOptions.Vertical) : input.y; } }
    public Vector2 Direction { get { return new Vector2(Horizontal, Vertical); } }

    public float HandleRange
    {
        get { return handleRange; }
        set { handleRange = Mathf.Abs(value); }
    }

    public float DeadZone
    {
        get { return deadZone; }
        set { deadZone = Mathf.Abs(value); }
    }

    public AxisOptions AxisOptions { get { return AxisOptions; } set { axisOptions = value; } }
    public bool SnapX { get { return snapX; } set { snapX = value; } }
    public bool SnapY { get { return snapY; } set { snapY = value; } }

    [SerializeField] private float handleRange = 1;
    [SerializeField] private float deadZone = 0;
    [SerializeField] private AxisOptions axisOptions = AxisOptions.Both;
    [SerializeField] private bool snapX = false;
    [SerializeField] private bool snapY = false;

    [SerializeField] protected RectTransform background = null;
    [SerializeField] private RectTransform handle = null;
    private RectTransform baseRect = null;

    private Canvas canvas;
    private Camera cam;

    private Vector2 input = Vector2.zero;

    protected virtual void Start()
    {
        HandleRange = handleRange;
        DeadZone = deadZone;
        baseRect = GetComponent<RectTransform>();
        canvas = GetComponentInParent<Canvas>();
        if (canvas == null)
            Debug.LogError("The Joystick is not placed inside a canvas");

        Vector2 center = new Vector2(0.5f, 0.5f);
        background.pivot = center;
        handle.anchorMin = center;
        handle.anchorMax = center;
        handle.pivot = center;
        handle.anchoredPosition = Vector2.zero;
    }

    public virtual void OnPointerDown(PointerEventData eventData)
    {
        OnDrag(eventData);
    }

    public void OnDrag(PointerEventData eventData)
    {
        cam = null;
        if (canvas.renderMode == RenderMode.ScreenSpaceCamera)
            cam = canvas.worldCamera;

        Vector2 position = RectTransformUtility.WorldToScreenPoint(cam, background.position);
        Vector2 radius = background.sizeDelta / 2;
        input = (eventData.position - position) / (radius * canvas.scaleFactor);
        FormatInput();
        HandleInput(input.magnitude, input.normalized, radius, cam);
        handle.anchoredPosition = input * radius * handleRange;
    }

    protected virtual void HandleInput(float magnitude, Vector2 normalised, Vector2 radius, Camera cam)
    {
        if (magnitude > deadZone)
        {
            if (magnitude > 1)
                input = normalised;
        }
        else
            input = Vector2.zero;
    }

    private void FormatInput()
    {
        if (axisOptions == AxisOptions.Horizontal)
            input = new Vector2(input.x, 0f);
        else if (axisOptions == AxisOptions.Vertical)
            input = new Vector2(0f, input.y);
    }

    private float SnapFloat(float value, AxisOptions snapAxis)
    {
        if (value == 0)
            return value;

        if (axisOptions == AxisOptions.Both)
        {
            float angle = Vector2.Angle(input, Vector2.up);
            if (snapAxis == AxisOptions.Horizontal)
            {
                if (angle < 22.5f || angle > 157.5f)
                    return 0;
                else
                    return (value > 0) ? 1 : -1;
            }
            else if (snapAxis == AxisOptions.Vertical)
            {
                if (angle > 67.5f && angle < 112.5f)
                    return 0;
                else
                    return (value > 0) ? 1 : -1;
            }
            return value;
        }
        else
        {
            if (value > 0)
                return 1;
            if (value < 0)
                return -1;
        }
        return 0;
    }

    public virtual void OnPointerUp(PointerEventData eventData)
    {
        input = Vector2.zero;
        handle.anchoredPosition = Vector2.zero;
    }

    protected Vector2 ScreenPointToAnchoredPosition(Vector2 screenPosition)
    {
        Vector2 localPoint = Vector2.zero;
        if (RectTransformUtility.ScreenPointToLocalPointInRectangle(baseRect, screenPosition, cam, out localPoint))
        {
            Vector2 pivotOffset = baseRect.pivot * baseRect.sizeDelta;
            return localPoint - (background.anchorMax * baseRect.sizeDelta) + pivotOffset;
        }
        return Vector2.zero;
    }
}

public enum AxisOptions { Both, Horizontal, Vertical }

--> Joystick.cs

enter image description here

enter image description here

enter image description here enter image description here enter image description here

enter image description here

enter image description here

\$\endgroup\$
11
  • \$\begingroup\$ Where do you call Get3DJoystickPodition? Do you see any errors in your console log? Can you show us where you've placed this script and the joystick in your scene, and how you've configured each in the Inspector? Don't forget to tag your question unity & c#! \$\endgroup\$ – DMGregory Aug 27 '20 at 11:28
  • \$\begingroup\$ Get3DJoystickPosition is called at LineMissile.cs, I'll link the script(LineMissile.cs) and scene pictures. \$\endgroup\$ – HackrJ Aug 27 '20 at 11:49
  • \$\begingroup\$ In here, JoyPos class is the class where Get3DJoystickPosition is inside. \$\endgroup\$ – HackrJ Aug 27 '20 at 11:53
  • \$\begingroup\$ Please always share code as text, not as images. \$\endgroup\$ – DMGregory Aug 27 '20 at 11:54
  • \$\begingroup\$ Looks like you have some significant errors in your console log. Be sure to resolve those first, or include them in your question if you need help solving them. \$\endgroup\$ – DMGregory Aug 27 '20 at 11:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.