I am trying to make a turret that shoots at a specified target. However, all things I have tried have yielded strange results. I first tried from instantiating the bullet from the turrets rotation, which follows the player. This caused the bullet to shoot in a direction that only lined up with the player when above if using transform.up and right with transform.right. When following tutorials online I got even stranger results, with the bullet going in figures of eight. After trying to tweak the scripts, I got it to shoot in the same direction every time.
I also tried to change the rotation from both the bullet and shooter side, but all my solutions have failed.
I am sorry if this is such a simple problem, but I have found no answer.
This is generally the approach I would take, although I’m sure there are ways you can do it in less lines of code. This assumes your bullet points to the right by default, but if it doesn’t you can tweak the code or the bullet prefab to fix this.
void Shoot(){
//Get direction vector pointing at target
Vector2 directionToTarget = target.transform.position - transform.position;
//This assumes that your bullet sprite points to the right
//Get the angle above the horizontal where the target is
float angle = Vector3.Angle(Vector3.right, directionToTarget);
//This will always be positive, so lets flip the sign if it should be negative
if(target.transform.position.y < transform.position.y) angle *= -1;
//Create a rotation that will point towards the target
Quaternion bulletRotation = Quaternion.AngleAxis(angle, Vector3.forward);
//Spawn bullet
Instantiate(bulletPrefab, transform.position, bulletRotation);
}