Menu
CoddyTech

קצב אש

שיעור 11 מתוך 25 בקורס משחק Unity: הגנת מגדלים של Coddy.

כל מגדל יורה פעם בשנייה. מגדל חץ אמור לירות מהר יותר, ותותח, שמגיע בהמשך, לאט יותר, לכן הקצב הופך לשדה: יריות בשנייה. הזמן בין שתי יריות הוא 1 חלקי הקצב:

nextShot = Time.time + 1f / 4f; // 4 יריות בשנייה: מרווח של 0.25 שניות ביניהן

הקדם־הגדרה ArrowTower מגדירה את הקצב שלו ל־1.5: ירייה כל 0.67 שניות.

challenge icon

אתגר

קל

תן לכל צריח לירות בקצב שלו.

  1. ב־Tower, הוסף public float fireRate = 1.5f; (יריות לשנייה).
  2. לאחר ירייה, הגדר nextShot = Time.time + 1f / fireRate;.

לחץ על "שחק": החצים יורים שלוש יריות בכל שתי שניות. לאחר מכן לחץ על "בדיקה".

נסו בעצמכם

using UnityEngine;

public class Tower : MonoBehaviour
{
    public float range = 4f;
    public int damage = 2;
    [SerializeField] private Transform head;
    [SerializeField] private float turnSpeed = 270f;
    [SerializeField] private Projectile projectilePrefab;

    private Enemy target;
    private float nextShot;

    void Update()
    {
        Enemy found = FindTarget();
        if (found != null && found != target)
        {
            Debug.Log("Target: " + found.name);
        }
        target = found;
        if (target == null)
        {
            return;
        }

        Aim();
        if (Time.time >= nextShot)
        {
            Fire();
            nextShot = Time.time + 1f;
        }
    }

    Enemy FindTarget()
    {
        Enemy nearest = null;
        float nearestDistance = range;
        foreach (Enemy enemy in Enemy.All)
        {
            float distance = Vector3.Distance(transform.position, enemy.transform.position);
            if (distance <= nearestDistance)
            {
                nearest = enemy;
                nearestDistance = distance;
            }
        }
        return nearest;
    }

    void Aim()
    {
        Vector3 direction = target.transform.position - head.position;
        direction.y = 0f;
        Quaternion look = Quaternion.LookRotation(direction);
        head.rotation = Quaternion.RotateTowards(head.rotation, look, turnSpeed * Time.deltaTime);
    }

    void Fire()
    {
        Projectile shot = Instantiate(projectilePrefab, head.position + head.forward * 0.6f, Quaternion.identity);
        shot.Launch(target.transform, damage);
    }
}

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

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