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:
Line 10 is your problem. Subtracting one axis from another does not give an angle. In fact, it is mathematically meaningless.
Basic trigonometry tells us that the tangent of an angle is the opposite side over the adjacent. Remember TANOA from algebra in school?
The function I suggested is called Mathf.Atan2() for a reason: it takes 2 coordinates and returns you the arctangent, which is the inverse of the tangent. In other words, it maps from two orthogonal axis to an angle.
This means that th…
Sine/Cosine/Atan2 (sin/cos/atan2) and rotational familiarity and conventions
This is actually an extremely important and teachable point… games are all over the place on this point, and every engine is a little different. For instance Unity is a left-handed engine (look up what that means on google), and it has conventions about what rotations do and which way is considered “zero.”
I try to make most of my games have zero point directly north with angles going clockwise, a throwback to olden day sprite systems, but any mathematics text or scientific text will have zero…
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: