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 Real Madrid remonta a la Roma, pero sigue sin convencer: ¿tiene Vinícius los días contados?

El Real Madrid remonta a la Roma, pero sigue sin convencer: ¿tiene Vinícius los días contados? Ayer el Real Madrid consiguió una victoria frente a la Roma en un partido…

El Barça está por encima de Messi, señor Gaspart, pero su historia más gloriosa lleva su nombre

JOAN GASPART a LEO MESSI Gaspart, Messi y el Barça: el club está por encima de todos, pero su historia no se puede borrar «¿Quién se ha creído? Que vaya…

Deja una respuesta

You Missed

El Real Madrid remonta a la Roma, pero sigue sin convencer: ¿tiene Vinícius los días contados?

  • Por admin
  • octubre 15, 2026
  • 17 views
El Real Madrid remonta a la Roma, pero sigue sin convencer: ¿tiene Vinícius los días contados?

El Barça está por encima de Messi, señor Gaspart, pero su historia más gloriosa lleva su nombre

  • Por admin
  • octubre 13, 2026
  • 15 views
El Barça está por encima de Messi, señor Gaspart, pero su historia más gloriosa lleva su nombre

Mbappé desafía al Bernabéu y Mourinho lo defiende: ¿castigo justo o caza mediática?

  • Por admin
  • octubre 10, 2026
  • 49 views
Mbappé desafía al Bernabéu y Mourinho lo defiende: ¿castigo justo o caza mediática?
El último baile del 10

Criticar a Lamine por su fútbol, sí; cuestionar que sea español, no.

  • Por admin
  • octubre 5, 2026
  • 53 views
Criticar a Lamine por su fútbol, sí; cuestionar que sea español, no.

Cristiano y Portugal: una historia demasiado grande para terminar de esta manera

  • Por admin
  • octubre 4, 2026
  • 23 views
Cristiano y Portugal: una historia demasiado grande para terminar de esta manera