How to get direction of player

Hello I am making a top down 3D game and I am trying to get the direction of the player so the enemy can shoot at them but I dont know how please help heres the code at the moment it doesn’t really work

enemy = GameObject.FindGameObjectWithTag(“Enemy”);


gameObject.transform.rotation = enemy.transform.rotation;

    rb.velocity = gameObject.transform.forward * magicSpee

The key parts will be:

  • subtracting the two positions to get a relative vector
  • using that vector directly to move
  • possibly converting that vector to an angle to rotate things like gun barrels, etc.

You may be able to simply drive transform.forward (or transform.up when in 2D) equal to your movement vector.

Here’s more notes for this extremely common task:

Otherwise, use Mathf.Atan2() to derive heading from cartesian coordinates:

Sine/Cosine/Atan2 (sin/cos/atan2) and rotational familiarity and conventions

I would start with any one of the thousands of Youtube tutorials for “how to aim bullets” or “how to target enemies”

If tutorial videos are insufficient then absolutely nothing in this little text box will be helpful either.

Imphenzia: How Did I Learn To Make Games: