2D raycast shooting in the wrong direction

Hi, I am making a 2D topdown game. And I got stuck with raycasting. I want to shoot a racyast from an enemy to the position of the player. The problem is that the raycast is going in the wrong direction, but slightly follows the player’s movement. I have been trying to find a solution, but with no luck. Thank you in advance if you know the solution! :slight_smile:

Here is the code and the image:


using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyRaycasting : MonoBehaviour {

    public float raycastDistance = 100f;
    public GameObject player;
    public GameObject enemy;
    private Vector2 playerPos;
    private Vector2 enemyPos;
    private Vector2 raycastDirection;

    public LayerMask whomstHit;

    [SerializeField]
    private bool showRaycast;

    void Start() {

    }

    void FixedUpdate() {
        playerPos = new Vector2(player.transform.position.x, player.transform.position.y);
        enemyPos = new Vector2(enemy.transform.position.x, enemy.transform.position.y);
    
        Raycast(enemyPos, playerPos);
    }

    void Raycast(Vector2 origin, Vector2 direction)
    {
        RaycastHit2D hit = Physics2D.Raycast(origin, direction, raycastDistance, whomstHit);

        if (hit.collider != null)
        {
            Debug.Log("Hit object " + hit.collider.name);
        }

        if (showRaycast == true)
        {
            Debug.DrawRay(origin, hit.point, Color.red);
        }
    }
}

The main idea of Raycasting is to specify the correct position of target ( in your case, it is your player, right? ) So for this line in FixedUpdate()
playerPos = new Vector2(player.transform.position.x, player.transform.position.y);
Write playerPos = new Vector2(player.transform.position.x-enemy.transform.position.x, player.transform.position.y-enemy.transform.position.y);

Notice how I subtracted the enemy’s position from our player’s position.