Hello,
I started making a little game in unity a few days ago. It was very easy and understandable for me. But now I am stuck at one position. My Enemys shoot (Top-Down 2D Shooter) in the players direction. But they even do it if walls are between them. My question might be very easy to answer, but after several hours of searching I could not find any help on the Internet.
How can I get the ray to shoot in the players direction?
I can shoot rays in every direction but not get the rays to fix on the players object.
Thanks for any help
Well, I think the answer depends on how are you shooting your rays? But if you are setting the velocity of the bullets directly, then you can do a little bit of vector math to figure out the direction
//So you spawn the bullet and then this would go into the bullet's behaviour script, Start method
Vector2 origin = this.transform.position;
Vector2 target = player.transform.position; //where player is a reference to the player's game object
Vector2 velocity = (origin - target).normalized * speed; //where speed is how fast you want the bullet to go
this.GetComponent<RigidBody2D>().velocity = velocity;
If you are modifying the transform directly you should be able to just lerp from it’s current location to the destination
Vector3 vecToPlayer = player.transform.position - enemy.transform.position will get a vector from the enemy to the player. Anytime you subtract a position from another position, you get a Vector from the second position to the first position.
vecToPlayer.normalized will resize the vector so it is only 1 unit long. When you “normalize” a vector, you are basically turning a position or offset into a direction.
To make this one short code statement, (player.transform.position - enemy.transform.position).normalized is the direction from the enemy to the player.
Yes, if you add a public GameObject to that class, you will see the public GameObject variable in Unity. You can drag-and-drop the player or enemy into the public variable spot in the Unity inspector.