Menu
CoddyTech

קפיצה

שיעור 3 מתוך 20 בקורס משחק Unity: נתיבי שמיים של Coddy.

כעת הרץ קופץ. ל־CharacterController אין כוח כבידה משלו: הסקריפט שלך שומר מהירות אנכית ונע לפיה בכל פריים.

כוח הכבידה משנה את המהירות הזאת בכל פריים. כשהרץ עומד על הקרקע (controller.isGrounded), שמור על מהירות קטנה כלפי מטה של -2 כדי שהוא יישאר צמוד לכביש:

if (controller.isGrounded && fallSpeed < 0f) fallSpeed = -2f;
fallSpeed += gravity * Time.deltaTime;

כדי להגיע לגובה h תחת כוח כבידה g, הקפיצה מתחילה במהירות Mathf.Sqrt(h * -2f * g). עם גובה קפיצה של 1.6 וכוח כבידה חזק של -40, הרץ קופץ לגובה וצונח במהירות, מה שמתאים למשחק שבו דברים נעים לעברך:

bool jump = Input.GetKeyDown(KeyCode.W) || Input.GetKeyDown(KeyCode.UpArrow) || Input.GetKeyDown(KeyCode.Space);
if (jump && controller.isGrounded)
{
    fallSpeed = Mathf.Sqrt(jumpHeight * -2f * gravity);
}

לתנועה יש עכשיו גם רכיב y: fallSpeed * Time.deltaTime.

challenge icon

אתגר

קל
  1. הוסיפו את public float jumpHeight = 1.6f;, את public float gravity = -40f; ואת private float fallSpeed; ל־Runner.
  2. אחרי מקשי הנתיבים, קראו את מקשי הקפיצה (W, Up, Space) וקפצו רק כאשר controller.isGrounded.
  3. לפני targetX, הוסיפו את שתי שורות הכבידה שמופיעות למעלה.
  4. צרו את התנועה באמצעות new Vector3(x - transform.position.x, fallSpeed * Time.deltaTime, 0f).

נסו בעצמכם

using UnityEngine;

public class Runner : MonoBehaviour
{
    public float laneWidth = 2.5f;
    public float laneSpeed = 16f;

    public int lane;

    private CharacterController controller;

    void Start()
    {
        controller = GetComponent<CharacterController>();
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.A) || Input.GetKeyDown(KeyCode.LeftArrow)) lane = Mathf.Max(-1, lane - 1);
        if (Input.GetKeyDown(KeyCode.D) || Input.GetKeyDown(KeyCode.RightArrow)) lane = Mathf.Min(1, lane + 1);

        float targetX = lane * laneWidth;
        float x = Mathf.MoveTowards(transform.position.x, targetX, laneSpeed * Time.deltaTime);
        Vector3 move = new Vector3(x - transform.position.x, 0f, 0f);
        controller.Move(move);
    }
}

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

תרגלו בעצמכם: Unity אונליין