Menu
CoddyTech

סיכום: החלפת קלט

חלק מהיחידה בונים משחקים אמיתיים במסלול ה-Unity של Coddy. שיעור 47 מתוך 56.

challenge icon

אתגר

בינוני

השרביט הזה ליצירת בועות נכתב עבור המחלקה הישנה Input. הוא עובד בפרויקט שמוגדר ל־Both, אבל הפרויקט הזה מוגדר כמו פרויקט חדש של Unity 6 (Active Input Handling: Input System Package): לחצו על Play והקריאה הראשונה ל־Input זורקת InvalidOperationException. הסבו אותו ל־Input System, תוך שמירה על כל מה שהוא עושה:

  • החצים או WASD מזיזים את השרביט ברחבי המדשאה במהירות של speed יחידות לשנייה, בלי לנוע מהר יותר באלכסון.
  • לחיצה על Jump יוצרת בועה 1.5 יחידות מעל השרביט. כל עוד Jump מוחזק, הבועה גדלה בקצב של growRate לשנייה, עד לגודל maxSize. כשמשחררים, גודל הבועה נרשם ביומן, למשל Bubble: 0.8.
  • לחיצה על הכפתור השמאלי של העכבר מפוצצת את כל הבועות ורושמת ביומן כמה היו, למשל Popped 3.

השתמשו בפעולות Move ו־Jump של הפרויקט וב־Mouse.current, וודאו שלא נשארת בסקריפט אף קריאה ל־Input.. לחצו על Play ונסו, ואז לחצו על Check.

נסו בעצמכם

using UnityEngine;

public class Wand : MonoBehaviour
{
    public float speed = 4f;
    public float growRate = 1f;
    public float maxSize = 1.5f;
    public GameObject bubblePrefab;

    private Transform bubble;

    void Update()
    {
        Vector3 move = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical"));
        transform.position += move.normalized * speed * Time.deltaTime;

        if (Input.GetButtonDown("Jump"))
        {
            bubble = Instantiate(bubblePrefab, transform.position + Vector3.up * 1.5f, Quaternion.identity).transform;
        }
        if (Input.GetButton("Jump") && bubble != null)
        {
            float size = Mathf.Min(bubble.localScale.x + growRate * Time.deltaTime, maxSize);
            bubble.localScale = Vector3.one * size;
        }
        if (Input.GetButtonUp("Jump") && bubble != null)
        {
            Debug.Log("Bubble: " + bubble.localScale.x.ToString("F1"));
            bubble = null;
        }

        if (Input.GetMouseButtonDown(0))
        {
            GameObject[] bubbles = GameObject.FindGameObjectsWithTag("Bubble");
            foreach (GameObject b in bubbles) Destroy(b);
            Debug.Log("Popped " + bubbles.Length);
        }
    }
}

כל השיעורים ביחידה בונים משחקים אמיתיים