Set Instanatiated Object's Rotation Towards Player
This is for a 2D game. I have an enemy that shoots a laser beam and I want the rotation of the beam to face towards whatever the player's current position is. My code so far is the following, but it's also possible that this is all more complicated than it needs to be. I'm just looking at some advice on what the correct way is to go about this.
public void Projectile1()
{
Vector3 myLocation = projectile1.transform.position;
Vector3 targetLocation = followTarget.transform.position;
myLocation.z = targetLocation.z;
Vector3 vectorToTarget = (targetLocation - myLocation);
Vector3 RotatedVectorToTarget = Quaternion.Euler(0,0,90) * vectorToTarget;
Quaternion targetRotation = Quaternion.LookRotation(Vector3.forward, RotatedVectorToTarget);
Instantiate(projectile1, projectile1Position.transform.position, targetRotation);
}
followTarget is the player's transform, projectile1Position is a transform of where the laser spawns, projectile1 is the laser gameobject. Right now it's just firing the laser in some random direction that doesn't seem to match up at all with the player's position.
Answer by qbflack2 · May 28, 2021 at 08:13 PM
I have never made a 2D game, but in a 3D one at least, using transform.LookAt(target); will make the object this script is attached to look at the target that is listed.
Your answer
Follow this Question
Related Questions
Problem with projectile rotation - 2D 0 Answers
More problems with arrow shooting 0 Answers
2D TopDown rotating a gun according to its parent position, ON MOBILE, not PC, 0 Answers
Shortest Rotation Path at Constant Speed 1 Answer
Using quaternions in 2D to follow a rotation. Both question and an Answer. 0 Answers