Pantalla táctil Unity

Aquí vamos aprender a como incorporar una pantalla táctil para nuestro juego, en mi caso será un volante, así que vamos a ello

Aquí tenemos nuestro Unity lo que vamos hacer es añadir un canvas y una imagen

Todavía nos queda un poquito ya aunque le diéramos al Play no funcionara nuestro Volante y nosotros lo que queremos es que se mueva , Así que vamos a crear un Create Empty

Lo llamamos control Pantalla y dentro creamos un Script al que vamos a llamar SteeringWheel

Y dentro del Script pegamos el siguiente código

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using System.Collections;
  
public class SteeringWheel : MonoBehaviour
{
    public Graphic UI_Element;
  
    RectTransform rectT;
    Vector2 centerPoint;
  
    public float maximumSteeringAngle = 200f;
    public float wheelReleasedSpeed = 200f;
  
    float wheelAngle = 0f;
    float wheelPrevAngle = 0f;
  
    bool wheelBeingHeld = false;
  
    public float GetClampedValue()
    {
        // returns a value in range [-1,1] similar to GetAxis("Horizontal")
        return wheelAngle / maximumSteeringAngle;
    }
  
    public float GetAngle()
    {
        // returns the wheel angle itself without clamp operation
        return wheelAngle;
    }
  
    void Start()
    {
        rectT = UI_Element.rectTransform;
        InitEventsSystem();
    }
  
    void Update()
    {
        // If the wheel is released, reset the rotation
        // to initial (zero) rotation by wheelReleasedSpeed degrees per second
        if( !wheelBeingHeld && !Mathf.Approximately( 0f, wheelAngle ) )
        {
            float deltaAngle = wheelReleasedSpeed * Time.deltaTime;
            if( Mathf.Abs( deltaAngle ) > Mathf.Abs( wheelAngle ) )
                wheelAngle = 0f;
            else if( wheelAngle > 0f )
                wheelAngle -= deltaAngle;
            else
                wheelAngle += deltaAngle;
        }
  
        // Rotate the wheel image
        rectT.localEulerAngles = Vector3.back * wheelAngle;
         
        //Debug.Log("Steering Value: " + GetClampedValue());
    }
  
    void InitEventsSystem()
    {
        // Warning: Be ready to see some extremely boring code here :-/
        // You are warned!
        EventTrigger events = UI_Element.gameObject.GetComponent<EventTrigger>();
  
        if( events == null )
            events = UI_Element.gameObject.AddComponent<EventTrigger>();
  
        if( events.triggers == null )
            events.triggers = new System.Collections.Generic.List<EventTrigger.Entry>();
  
        EventTrigger.Entry entry = new EventTrigger.Entry();
        EventTrigger.TriggerEvent callback = new EventTrigger.TriggerEvent();
        UnityAction<BaseEventData> functionCall = new UnityAction<BaseEventData>( PressEvent );
        callback.AddListener( functionCall );
        entry.eventID = EventTriggerType.PointerDown;
        entry.callback = callback;
  
        events.triggers.Add( entry );
  
        entry = new EventTrigger.Entry();
        callback = new EventTrigger.TriggerEvent();
        functionCall = new UnityAction<BaseEventData>( DragEvent );
        callback.AddListener( functionCall );
        entry.eventID = EventTriggerType.Drag;
        entry.callback = callback;
  
        events.triggers.Add( entry );
  
        entry = new EventTrigger.Entry();
        callback = new EventTrigger.TriggerEvent();
        functionCall = new UnityAction<BaseEventData>( ReleaseEvent );//
        callback.AddListener( functionCall );
        entry.eventID = EventTriggerType.PointerUp;
        entry.callback = callback;
  
        events.triggers.Add( entry );
    }
  
    public void PressEvent( BaseEventData eventData )
    {
        // Executed when mouse/finger starts touching the steering wheel
        Vector2 pointerPos = ( (PointerEventData) eventData ).position;
  
        wheelBeingHeld = true;
        centerPoint = RectTransformUtility.WorldToScreenPoint( ( (PointerEventData) eventData ).pressEventCamera, rectT.position );
        wheelPrevAngle = Vector2.Angle( Vector2.up, pointerPos - centerPoint );
    }
  
    public void DragEvent( BaseEventData eventData )
    {
        // Executed when mouse/finger is dragged over the steering wheel
        Vector2 pointerPos = ( (PointerEventData) eventData ).position;
  
        float wheelNewAngle = Vector2.Angle( Vector2.up, pointerPos - centerPoint );
        // Do nothing if the pointer is too close to the center of the wheel
        if( Vector2.Distance( pointerPos, centerPoint ) > 20f )
        {
            if( pointerPos.x > centerPoint.x )
                wheelAngle += wheelNewAngle - wheelPrevAngle;
            else
                wheelAngle -= wheelNewAngle - wheelPrevAngle;
        }
        // Make sure wheel angle never exceeds maximumSteeringAngle
        wheelAngle = Mathf.Clamp( wheelAngle, -maximumSteeringAngle, maximumSteeringAngle );
        wheelPrevAngle = wheelNewAngle;
    }
  
    public void ReleaseEvent( BaseEventData eventData )
    {
        // Executed when mouse/finger stops touching the steering wheel
        // Performs one last DragEvent, just in case
        DragEvent( eventData );
  
        wheelBeingHeld = false;
    }
}

Aquí ya tendríamos nuestro código, yo os voy a poner los errores que me salieron y como areglarlos

quizas a vosotros no os salga o si pero aquí teneis el resultado de este Script copiado

Estos serian nuestros errores vamos air solucionándolo poco a poco

Solo nos quedarían 29 fallos de 30 aun son muchísimos, y aquí que hemos hecho muy facil hemos puesto

using UnityEngine.UI;

Y que es:

El sistema UI le permite a usted crear interfaces de usuario rápidas e intuitivas. Esta es una introducción a las características principales del sistema UI de Unity.

De 29 Errores bajaron a 4 Errores, los errores bajaron significativamente añadiendo using UnityEngine.Events;

El sistema de eventos es una forma de enviar eventos a objetos en la aplicación en función de la entrada, ya sea teclado, mouse, toque o entrada personalizada . El Sistema de eventos consta de unos pocos componentes que trabajan juntos para enviar eventos.

Ahora vamos hacer que tengamos un nuevo error

Y ahora solucionaremos todo

Y ya lo tendríamos

Related Posts

El fútbol femenino español lo tiene todo menos una gran audiencia: ¿qué está fallando?

El fútbol femenino español tiene motivos para sentirse orgulloso, pero necesita seguir creciendo Para mí, el fútbol femenino español es algo de lo que podemos sentirnos profundamente orgullosos. Tenemos una…

La paradoja del fútbol español: el Barcelona juega con más españoles que el Real Madrid

El Barcelona se españoliza cada vez más, La Masía ahora Rodri refuerzan una identidad muy nacional Con el fichaje de Rodri, el Barcelona continúa aumentando el peso de los futbolistas…

Deja una respuesta

You Missed

El fútbol femenino español lo tiene todo menos una gran audiencia: ¿qué está fallando?

  • Por admin
  • agosto 19, 2026
  • 8 views
El fútbol femenino español lo tiene todo menos una gran audiencia: ¿qué está fallando?

La paradoja del fútbol español: el Barcelona juega con más españoles que el Real Madrid

  • Por admin
  • agosto 18, 2026
  • 9 views
La paradoja del fútbol español: el Barcelona juega con más españoles que el Real Madrid

Rodri por 60 millones y con 30 años: ¿fichajazo del Barcelona o demasiado riesgo?

  • Por admin
  • agosto 18, 2026
  • 7 views
Rodri por 60 millones y con 30 años: ¿fichajazo del Barcelona o demasiado riesgo?

Ferran Torres ficha por el PSG: ¿se arrepentirá el Barcelona de su salida?

  • Por admin
  • agosto 15, 2026
  • 23 views
Ferran Torres ficha por el PSG: ¿se arrepentirá el Barcelona de su salida?

LaLiga 2026-27: Real Madrid, Barcelona y Atlético luchan por el título

  • Por admin
  • agosto 15, 2026
  • 22 views
LaLiga 2026-27: Real Madrid, Barcelona y Atlético luchan por el título

Ferran al PSG: una cosa son los colores y otra muy distinta el dinero

  • Por admin
  • agosto 15, 2026
  • 28 views
Ferran al PSG: una cosa son los colores y otra muy distinta el dinero