Home > Enterprise >  I'm trying to map my laptop trackpad to a slider
I'm trying to map my laptop trackpad to a slider

Time:07-15

I'm a beginner in Unity, currently working on mapping the Y axis on the trackpad to control a slider value. With Debug.Log, I can see the value returning, but then it doesn't get to the slider. I am not sure what I am missing, since it seems like a fairly simple script... here's the code

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

    public class SliderControl : MonoBehaviour
    {
        public Vector2 screenPosition;
    
        public Slider slider;
    
        void Start()
        {
            slider = GetComponent<Slider>();
        }
    
        // Update is called once per frame
        void Update()
        {
            screenPosition = Input.mousePosition;
            Debug.Log(Input.mousePosition);
    
            screenPosition.y = slider.value;
        }
    }

oh and by the way, doesn't give me any errors at all

Also it's my first time posting in here, if there's any policy I haven't respected please let me know!

CodePudding user response:

The problem is that instead of assigning the y value of the mouse position to the slider value, you are doing the opposite. Also remember that as it is, the slider will be extremely sensitive, because the position of the mouse can also be equal to (0, 2000). In the correct code, I'll add a variable that you can use to make the slider more or less sensitive.

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

public class SliderControl : MonoBehaviour
{
    public Vector2 screenPosition;
    public Slider slider;
    public float length = 50;

    void Start()
    {
        slider = GetComponent<Slider>();
        //If you want, you can set the value of "length" with the maxValue of the scroller.
        length = slider.maxValue;
    }

    // Update is called once per frame
    void Update()
    {
        screenPosition = Input.mousePosition;
        slider.value = screenPosition.y / Screen.height * length;
    }
}
  • Related