Movimiento de clic y dirección de la interfaz de usuario del juego móvil Unity

Clic de un botón

1.1 Nueva interfaz de usuario -> Botón

1.2 Haga clic derecho en el botón para agregar un objeto vacío

1.3 Crear un script y montarlo en el objeto vacío

 Agregue un método de clic al contenido del script para controlar la visualización y ocultación de objetos.

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

public class NewMonoBehaviour : MonoBehaviour
{
   public GameObject player;//获取物体
    private bool isActivity = true;
    private void Awake()
    {
        player = GameObject.Find("Player");
    }

    // Start is called before the first frame update
    void Start()
    {
    }

    void Update()
    {
    }

    // 按钮点击事件
    public void OnMyClick()
    {
        isActivity = !isActivity;
        //显示或者隐藏
        player.SetActive(isActivity);
    }
}

1.4 Asocie la posición Al hacer clic en el botón con un objeto vacío y seleccione el método de script OnMyClick() del objeto vacío.

1.5 Después de ejecutar, es posible controlar la visualización y ocultación de objetos.

Dos teclas de dirección controlan el movimiento.

2.1 Agregar cuatro botones de dirección

 2.2 Agregar un script y montarlo en cuatro botones al mismo tiempo

2.3 Escriba un script para determinar en qué botón se hizo clic según el nombre del botón, a fin de determinar en qué dirección moverse.

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

public class Controll : MonoBehaviour,IPointerDownHandler, IPointerUpHandler
{
    public Rigidbody2D rbody;//获取刚体

    private void Awake()
    {
 
        rbody = GameObject.Find("Player").GetComponent<Rigidbody2D>();
    }

    void Start()
    {
      
    }

    // Update is called once per frame
    void Update()
    {
        if (isMove) {
            move();
        }        
    }

    public bool isMove = false;//是否移动

    public void OnPointerDown(PointerEventData eventData)
    {
        isMove = true;
        getButton(eventData);
   
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        isMove = false;
    }

    //获取点击的哪个按钮,方向
    private void getButton(PointerEventData eventData) {
        GameObject gameObject = eventData.selectedObject;
        Debug.Log(gameObject.name);
        switch (gameObject.name) {
            case "ButtonUp":
                moveX = 0;
                moveY = 1;
                break;
            case "ButtonLeft":
                moveX = -1;
                moveY = 0;
                break;
            case "ButtonBottom":
                moveX = 0;
                moveY = -1;
                break;
            case "ButtonRight":
                moveX = 1;
                moveY = 0;
                break;
            default:
                moveX = 0;
                moveY = 0;
                break;
        }
    }

    /**
     * 移动
     **/
    public float speed = 10f;//移动速度
    private int moveX;//方向 -1左 1右
    private int moveY;//方向 -1上 1下
    public void move() {
       
        Vector2 position = rbody.position;
        position.x += moveX * speed * Time.deltaTime;
        position.y += moveY * speed * Time.deltaTime;
        //transform.position = position;
        rbody.MovePosition(position);
    }
}

2.4 Cuando corres, puedes ver que los objetos se pueden mover hacia arriba, abajo, izquierda y derecha.

2.5 Resumen:

  • El script implementa la interfaz MonoBehaviour, IPointerDownHandler e IPointerUpHandler para generar el evento de prensa.
  • Obtenga el objeto a través de GameObject.Find("Player").GetComponent<Rigidbody2D>()
  • Agregue la variable si se debe mover isMove y determine si se debe interceptar el movimiento en el método Actualizar.
  • Cuando se presiona OnPointerDown, use eventData.selectedObject para obtener en qué botón se hizo clic para determinar las direcciones arriba, abajo, izquierda y derecha.
  • Agregue juicio de dirección, asigne valor cuando se presiona el botón, int moveX; // Dirección - 1 izquierda 1 derecha int moveY; // Dirección - 1 arriba 1 abajo
  • Cuando se levanta el botón OnPointerUp, ivMove se vuelve falso y la posición del movimiento ya no se actualiza.

Supongo que te gusta

Origin blog.csdn.net/qq_29848853/article/details/132906159
Recomendado
Clasificación