U
U
Uncle Bogdan2021-09-30 20:11:45
Unity
Uncle Bogdan, 2021-09-30 20:11:45

Is the enemy shooting in the wrong direction?

You can see it best on video .

The enemy shoots in the wrong place and the arrow is turned crooked.
If the player runs, then the arrows start flying in the wrong direction at all.

How to fix it?

The code:

using UnityEngine;

public class ShotingEnemy : MonoBehaviour
{
    [Header("Settings")]
    [SerializeField] private float _distance;
    [SerializeField] private float _cooldown;

    [SerializeField] private StateEnemy _prefab;
    [SerializeField] private Transform _target;

    private float _currentTime;

    private bool CanShot = true;

    private void Update()
    {
        transform.LookAt(_target.position, Vector3.up);

        if(CanShot && (_target.position - transform.position).magnitude <= _distance)
        {
            Shot();

            CanShot = false;
        }

        if(!CanShot)
        {
            _currentTime += Time.deltaTime;
        }

        if(_currentTime >= _cooldown)
        {
            CanShot = true;
            _currentTime = 0;
        }
    }

    private void Shot()
    {
        var bullet = Instantiate(_prefab, transform.position, Quaternion.identity);

        bullet.transform.LookAt(_target.position);
    }
}


Here is the code on the arrow:

using UnityEngine;

public class MoveForward : MonoBehaviour
{
    [SerializeField] private float _speed;

    private void Update()
    {
        transform.Translate(-transform.forward);
    }
}


Thanks in advance. For any questions write!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
KraGen.Developer, 2021-09-30
@KraGenDeveloper

I know what's wrong BUT for the arrow to fly along the enemy's gaze vector, you need NOT

var bullet = Instantiate(_prefab, transform.position, Quaternion.identity);

BUT
var bullet = Instantiate(_prefab, transform.forward, Quaternion.identity);

so the arrow will fly at the sight of the enemy

M
MrAfitol, 2021-09-30
@MrAfitol

Do you have zero coordinates and rotation in the arrow prefab?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question