[Résolu] Déplacement objet sur Un axe (Y) avec min et max

Toutes les questions sur le développement Mobile, y compris la partie script.
Leuprochon
Messages : 60
Inscription : 04 Déc 2017 19:12

[Résolu] Déplacement objet sur Un axe (Y) avec min et max

Message par Leuprochon » 29 Nov 2019 13:37

Bonjour à tous,

Alors pour mon application j'aimerais que l'utilisateur puisse faire glisser un objet (avec le doigt) sur l'axe Y entre 2 valeurs (min et max).

Dans un premier temps j'ai essayé l'outil LeanTouch. Ils ont un script qui fait ce que je veux (le déplacement) mais le script est vraiment complexe et je n'arrive pas à limiter le déplacement en Y (il me déplace en X aussi) et à ajouter un min et un max.

Du coup j'ai trouvé une autre solution (qui marche qu'à moitié, sinon je ne serai pas là ! ) et j'ai quelques problèmes :

- Je ne comprends pas pourquoi il me bouge les valeurs de X et Z. Même si c'est très peu par rapport à Y mon script influence quand même X et Z je ne sais pas pourquoi.
- Il prend en compte la position ou je clique, or je veux que la position du clique n'ait pas d'importance (je crois qu'il faut créer un offset ? Comment ça fonctionne?)
- Comment faire pour ajouter un effet comme un swipe ? Une translation fluide ?

Voici mon code (je vous mets également le code du LeanTouch si vous pensez que c'est plus simple. Il faut juste contraindre le mouvement en Y avec un max et un min):

Code : Tout sélectionner

using UnityEngine;

public class NewBehaviourScript : MonoBehaviour
{
    public Vector3 min;
    public Vector3 max;

    private float? lastMousePoint = null;
    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            lastMousePoint = Input.mousePosition.y;
        }
        else if (Input.GetMouseButtonUp(0))
        {
            lastMousePoint = null;
        }
        if (lastMousePoint != null)
        {
            float difference = Input.mousePosition.y - lastMousePoint.Value;
            Vector3 pos = transform.position;

            pos = new Vector3(pos.x, pos.y, pos.z);

            pos.y = Mathf.Clamp(pos.y + (difference / 188) * Time.deltaTime, min.y, max.y);
            transform.position = pos;
       
           lastMousePoint = Input.mousePosition.y;
        }
    }
}

Le code du LeanTouch :

Code : Tout sélectionner


using UnityEngine;

namespace Lean.Touch
{
	/// <summary>This component allows you to translate the current GameObject relative to the camera using the finger drag gesture.</summary>
	[HelpURL(LeanTouch.HelpUrlPrefix + "LeanDragTranslate")]
	[AddComponentMenu(LeanTouch.ComponentPathPrefix + "Drag Translate")]
	public class LeanDragTranslate : MonoBehaviour
	{
		/// <summary>The method used to find fingers to use with this component. See LeanFingerFilter documentation for more information.</summary>
		public LeanFingerFilter Use = new LeanFingerFilter(true);

		/// <summary>The camera the translation will be calculated using.\n\nNone = MainCamera.</summary>
		[Tooltip("The camera the translation will be calculated using.\n\nNone = MainCamera.")]
		public Camera Camera;

		/// <summary>If you want this component to change smoothly over time, then this allows you to control how quick the changes reach their target value.
		/// -1 = Instantly change.
		/// 1 = Slowly change.
		/// 10 = Quickly change.</summary>
		[Tooltip("If you want this component to change smoothly over time, then this allows you to control how quick the changes reach their target value.\n\n-1 = Instantly change.\n\n1 = Slowly change.\n\n10 = Quickly change.")]
		public float Dampening = -1.0f;

		[HideInInspector]
		[SerializeField]
		private Vector3 remainingTranslation;

		/// <summary>If you've set Use to ManuallyAddedFingers, then you can call this method to manually add a finger.</summary>
		public void AddFinger(LeanFinger finger)
		{
			Use.AddFinger(finger);
		}

		/// <summary>If you've set Use to ManuallyAddedFingers, then you can call this method to manually remove a finger.</summary>
		public void RemoveFinger(LeanFinger finger)
		{
			Use.RemoveFinger(finger);
		}

		/// <summary>If you've set Use to ManuallyAddedFingers, then you can call this method to manually remove all fingers.</summary>
		public void RemoveAllFingers()
		{
			Use.RemoveAllFingers();
		}
#if UNITY_EDITOR
		protected virtual void Reset()
		{
			Use.UpdateRequiredSelectable(gameObject);
		}
#endif
		protected virtual void Awake()
		{
			Use.UpdateRequiredSelectable(gameObject);
		}

		protected virtual void Update()
		{
			// Store
			var oldPosition = transform.localPosition;

			// Get the fingers we want to use
			var fingers = Use.GetFingers();

			// Calculate the screenDelta value based on these fingers
			var screenDelta = LeanGesture.GetScreenDelta(fingers);

			if (screenDelta != Vector2.zero)
			{
				// Perform the translation
				if (transform is RectTransform)
				{
					TranslateUI(screenDelta);
				}
				else
				{
					Translate(screenDelta);
				}
			}

			// Increment
			remainingTranslation += transform.localPosition - oldPosition;

			// Get t value
			var factor = LeanTouch.GetDampenFactor(Dampening, Time.deltaTime);

			// Dampen remainingDelta
			var newRemainingTranslation = Vector3.Lerp(remainingTranslation, Vector3.zero, factor);

			// Shift this transform by the change in delta
			transform.localPosition = oldPosition + remainingTranslation - newRemainingTranslation;

			// Update remainingDelta with the dampened value
			remainingTranslation = newRemainingTranslation;
		}

		private void TranslateUI(Vector2 screenDelta)
		{
			var camera = LeanTouch.GetCamera(Camera, gameObject);

			// Screen position of the transform
			var screenPoint = RectTransformUtility.WorldToScreenPoint(camera, transform.position);

			// Add the deltaPosition
			screenPoint += screenDelta;

			// Convert back to world space
			var worldPoint = default(Vector3);

			if (RectTransformUtility.ScreenPointToWorldPointInRectangle(transform.parent as RectTransform, screenPoint, camera, out worldPoint) == true)
			{
				transform.position = worldPoint;
			}
		}

		private void Translate(Vector2 screenDelta)
		{
			// Make sure the camera exists
			var camera = LeanTouch.GetCamera(Camera, gameObject);

			if (camera != null)
			{
				// Screen position of the transform
				var screenPoint = camera.WorldToScreenPoint(transform.position);

				// Add the deltaPosition
				screenPoint += (Vector3)screenDelta;

				// Convert back to world space
				transform.position = camera.ScreenToWorldPoint(screenPoint);
			}
			else
			{
				Debug.LogError("Failed to find camera. Either tag your camera as MainCamera, or set one in this component.", this);
			}
		}
	}
}

Dernière édition par Leuprochon le 04 Déc 2019 11:05, édité 1 fois.

Leuprochon
Messages : 60
Inscription : 04 Déc 2017 19:12

Re: Déplacement objet sur Un axe (Y) avec min et max

Message par Leuprochon » 04 Déc 2019 11:05

J'ai réussi à résoudre le problème. Une partie du problème était du au fait que je suis en RA, donc il faut que j'utilise le transform.localposition et non le transform.Position

Voici mon code si ça peut en aider certains :

Code : Tout sélectionner

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

public class NewBehaviourScript : MonoBehaviour
{

    private float deltaY;

    public Vector3 min;
    public Vector3 max;

    private float? lastMousePoint = null;
    private void Update()
    {

        if (Input.GetMouseButtonDown(0))
        {
            lastMousePoint = Input.mousePosition.y;
        }
        else if (Input.GetMouseButtonUp(0))
        {
            lastMousePoint = null;
        }
        if (lastMousePoint != null)
        {

            Debug.Log(transform.localPosition.x);
            float difference = lastMousePoint.Value - Input.mousePosition.y;

            transform.localPosition = (new Vector3(transform.localPosition.x, Mathf.Clamp(transform.localPosition.y - (difference / 400F) * Time.deltaTime, -0f, 0.0585f), transform.localPosition.z));

            lastMousePoint = Input.mousePosition.y;
        }
    }
}

Répondre

Revenir vers « Développement plateformes mobile Iphone et Android »