Search Unity

Управление на кнопках в 2D игре для телефона

Discussion in '2D' started by igor228isakov, Nov 28, 2018.

  1. igor228isakov

    igor228isakov

    Joined:
    Jul 31, 2018
    Posts:
    2
    Помогите пожалуйста с скриптом для управления 2д игры доя телефона. Нужно что бы персонаж прыгал вверх, шел вправо, влево...
    Скиньте скрипт, пожалуйста!
     
  2. vakabaka

    vakabaka

    Joined:
    Jul 21, 2014
    Posts:
    1,153
    I don't have any phone for testing, this just the script for jumping. If you can get it working then you can add to it other UI-Images and conditions for moving.

    Add UI-Image in the scene (later you can use it as picture for the "Jump" button). Add this script to the player with rigidbody2d and collider2d. Fill the scripts fields with objects. Try it with unity-remote or as builded app.
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5. using UnityEngine.EventSystems;
    6.  
    7. public class TouchCtrl : MonoBehaviour
    8. {
    9.     //add UI-Image in the scene and drag&drop it here
    10.     public GameObject jumpImage;
    11.     //drag&drop here EventSystem
    12.     public EventSystem eventSystem;
    13.     //drag&drop here Canvas (it should have Graphic Raycaster (Script) component)
    14.     public GraphicRaycaster canvasRaycaster;
    15.     Rigidbody2D rb;
    16.     bool canJump;
    17.     //make it bigger for testing (like 100)
    18.     public float jumpForce;
    19.  
    20.     void Start ()
    21.     {
    22.         rb = GetComponent<Rigidbody2D>();
    23.     }
    24.  
    25.     void Update ()
    26.     {
    27.         for (int i = 0; i < Input.touchCount; i++)
    28.         {
    29.             Touch touch = Input.GetTouch(i);
    30.             if (touch.phase == TouchPhase.Began)
    31.             {
    32.                 PointerEventData pointerEventData = new PointerEventData(eventSystem);
    33.                 pointerEventData.position = touch.position;
    34.                 List<RaycastResult> results = new List<RaycastResult>();
    35.                 canvasRaycaster.Raycast(pointerEventData, results);
    36.                 if (results != null)
    37.                 {
    38.                     foreach (RaycastResult result in results)
    39.                     {
    40.                         if (result.gameObject == jumpImage)
    41.                         {
    42.                             canJump = true;
    43.                         }
    44.                     }
    45.                 }
    46.             }
    47.         }
    48.     }
    49.  
    50.     void FixedUpdate ()
    51.     {
    52.         if (canJump)
    53.         {
    54.             canJump = false;
    55.             rb.AddForce(Vector2.up * jumpForce);
    56.         }
    57.     }
    58. }