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: مسارات السماء

تدرّب بنفسك: Playground لـ Unity