בלי פניית פרסה
שיעור 3 מתוך 14 בקורס משחק Unity: נחש תלת־ממדי של Coddy.
נחש שפונה מיד בחזרה פוגע בצוואר של עצמו, ולכן מתעלמים מפנייה לכיוון ההפוך. הכיוון ההפוך הוא הכיוון השלילי: כשהנחש נע ימינה, -direction הוא Vector3.left.
השוואה מול direction אינה מספיקה כאשר לחיצה משנה אותו מיד: בזמן תנועה ימינה, השחקן לוחץ על למעלה ואז על שמאלה, בתוך טיק אחד. הפנייה למעלה מותרת, ואז הפנייה שמאלה נבדקת מול הכיוון למעלה וגם היא מותרת, והצעד הבא חוזר דרך הצוואר.
לכן יש לשמור שני כיוונים: direction, הכיוון שבו הראש נע בפעם האחרונה, ו-nextDirection, הפנייה שממתינה לצעד הבא. מקש משנה את nextDirection לאחר השוואה מול direction, והצעד הופך את הפנייה הממתינה לממשית.
אתגר
קלמנע מהנחש לפנות ישר בחזרה אל צווארו.
- הוסף
private Vector3 nextDirection = Vector3.right;ואתvoid Turn(Vector3 newDirection): הגדר את nextDirection, אלא אםnewDirection == -direction. - ב־
Update(), כל מקש קורא ל־Turnעם הכיוון שלו במקום להגדיר את direction. - בתחילת
Step(), הגדרdirection = nextDirection;
לחץ על "שחק" ולחץ שמאלה בזמן תנועה ימינה: הנחש ממשיך לנוע ימינה. ואז לחץ על "בדיקה".
נסו בעצמכם
using UnityEngine;
using UnityEngine.InputSystem;
public class Snake : MonoBehaviour
{
public float tick = 0.15f; // שניות בין שני צעדים
private float timer;
private Vector3 direction = Vector3.right;
void Update()
{
Keyboard keyboard = Keyboard.current;
if (keyboard != null)
{
if (keyboard.upArrowKey.wasPressedThisFrame || keyboard.wKey.wasPressedThisFrame) direction = Vector3.forward;
if (keyboard.downArrowKey.wasPressedThisFrame || keyboard.sKey.wasPressedThisFrame) direction = Vector3.back;
if (keyboard.leftArrowKey.wasPressedThisFrame || keyboard.aKey.wasPressedThisFrame) direction = Vector3.left;
if (keyboard.rightArrowKey.wasPressedThisFrame || keyboard.dKey.wasPressedThisFrame) direction = Vector3.right;
}
timer += Time.deltaTime;
if (timer >= tick)
{
timer -= tick;
Step();
}
}
void Step()
{
transform.position += direction;
}
}
כל השיעורים ביחידה משחק Unity: נחש תלת־ממדי
תרגלו בעצמכם: Unity אונליין