0

Привет.

У меня есть скрипт лука

`using UnityEngine;

public class Bow : MonoBehaviour
{
    public GameObject arrowPrefab;
    public float launchForce;
    public Transform shotPoint;
    public Transform bow;

    public int damage;
    
    public float range;
    public float timeBtwShots;
    private float nextTimeToShoot;

    private GameObject curTarget;

    private void Start()
    {
        
    }

    void Update()
    {
        nextTimeToShoot += Time.deltaTime;
        
        if (curTarget != null)
        {
            Vector2 relative = curTarget.transform.position - bow.position;

            float angle = Mathf.Atan2(relative.y, relative.x) * Mathf.Rad2Deg;

            Vector3 rotation = new Vector3(0, 0, angle);

            bow.localRotation = Quaternion.Euler(rotation);
        }

        if (nextTimeToShoot >= timeBtwShots)
        {
            if (curTarget != null)
            {
                nextTimeToShoot = 0;
                
                Shoot();
            }
        }
        
        UpdateNearestEnemy();
    }

    public void Shoot()
    {
        if (curTarget != null)
        {
            Enemy enemyScript = curTarget.GetComponent<Enemy>();
            
            enemyScript.TakeDamage(damage);
        }
        GameObject newArrow = Instantiate(arrowPrefab, shotPoint.position, shotPoint.rotation);
        newArrow.GetComponent<Rigidbody2D>().velocity = transform.right * launchForce;
    }

    private void UpdateNearestEnemy()
    {
        GameObject currentNearestEnemy = null;

        float distance = Mathf.Infinity;

        foreach (GameObject enemy in Game.enemies)
        {
            if (enemy != null)
            {
                float _distance = (transform.position - enemy.transform.position).magnitude;

                if (_distance < distance)
                {
                    distance = _distance;
                    currentNearestEnemy = enemy;
                }   
            }
        }

        if (distance <= range)
        {
            curTarget = currentNearestEnemy;
        }
        else
        {
            curTarget = null;
        }
    }
}`

При выстреле из лука стрела летит просто в врага, а мне хотелось бы сделать ее траекторию так, чтобы при выстреле стрела летела вверх и приземлялась во врага.Вот фото траектории

Никак не могу понять что нужно добавить в скрипт, дабы получилась моя задумка. Буду рад любым ответам и решениям.

1
  • Эта штука называется баллистической траекторией, вот на Хабре, например, статья: habr.com/ru/articles/538952
    – Qwer
    9 авг в 8:07

1 ответ 1

2

Понял как это сделать, вот скрипт

`public class Archer : MonoBehaviour
{
    public static Archer instance;
    
    public GameObject arrowPrefab;
    public Transform shootPoint;
    
    public int damage;
    public float shootForce = 10f;
    
    private float shootTimer = 0f; // Текущее значение таймера
    public float shootInterval = 1f; // Интервал между выстрелами в секундах

    private const float G = 9.81f;

    public Transform targetEnemy; // Позиция противника

    private void Awake()
    {
        instance = this;
    }

    void Update()
    {
        FindClosestEnemy();
        
        shootTimer += Time.deltaTime; // Обновляем таймер

        if (shootTimer >= shootInterval)
        {
            ShootArrow(); // Выстреливаем стрелу
            shootTimer = 0f; // Сброс таймера
        }
    }

    void ShootArrow()
    {
        if (targetEnemy == null) return; // Не стреляем, если нет противников

        GameObject arrowInstance = Instantiate(arrowPrefab, shootPoint.position, Quaternion.identity);
        Rigidbody2D rb = arrowInstance.GetComponent<Rigidbody2D>();

        float dx = targetEnemy.position.x - shootPoint.position.x;
        float dy = targetEnemy.position.y - shootPoint.position.y;

        float angle = CalculateShootAngle(dx, dy);

        float vx = Mathf.Cos(angle) * shootForce;
        float vy = Mathf.Sin(angle) * shootForce;

        rb.velocity = new Vector2(vx, vy);
    }
    
    public void DealDamageToEnemy(Enemy enemy)
    {
        if (enemy != null)
        {
            enemy.TakeDamage(damage);
        }
    }
    
    float CalculateShootAngle(float dx, float dy)
    {
        float g = Mathf.Abs(Physics2D.gravity.y);
        float v2 = shootForce * shootForce;
        float underRoot = v2 * v2 - g * (g * dx * dx + 2 * dy * v2);

        if (underRoot < 0) 
        {
            Debug.LogWarning("Angle calculation error: Using default angle of 45 degrees");
            return Mathf.PI / 4;  // 45 градусов в радианах
        }

        float sqrtPart = Mathf.Sqrt(underRoot);

        float angle1 = Mathf.Atan((v2 + sqrtPart) / (g * dx));
        float angle2 = Mathf.Atan((v2 - sqrtPart) / (g * dx));

        // Выбираем угол, который ближе к горизонту
        if (Mathf.Abs(angle1) < Mathf.Abs(angle2))
            return angle1;
        else
            return angle2;
    }
    
    void FindClosestEnemy()
    {
        float closestDistance = float.MaxValue; // начальное значение максимально возможного расстояния

        GameObject[] enemies = GameObject.FindGameObjectsWithTag("Enemy");
        foreach (GameObject enemy in enemies)
        {
            float currentDistance = Vector2.Distance(transform.position, enemy.transform.position);
            if (currentDistance < closestDistance)
            {
                closestDistance = currentDistance;
                targetEnemy = enemy.transform;
            }
        }
    }
    
    public void UpgradeDamage(int upgradeAmount)
    {
        damage += upgradeAmount;
    }
}`

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.