Enemy's projectile is firing at the opposite direction when it's y-axis align with the player's
Hi, I am fairly new to unity and am currently facing a problem regarding my projectile's firing direction. I wanted the enemy to shoot a projectile aiming towards the player's current position and i achieved it by attaching a child gameobject with this script to the enemy public class HomingShots : MonoBehaviour {
[SerializeField] GameObject enemyLazerPrefab;
[SerializeField] float timeBetweenShots = 0.5f;
[SerializeField] float projectileSpeed = 6f;
bool firing = true;
Player player;
void Start ()
{
player = FindObjectOfType<Player>();
StartCoroutine(FiringCoroutine());
}
private void FixedUpdate()
{
if (player)
{
if (!firing)
{
firing = true;
StartCoroutine(FiringCoroutine());
}
transform.up = player.transform.position - transform.position;
}
else
{
firing = false;
player = FindObjectOfType<Player>();
}
}
IEnumerator FiringCoroutine()
{
while (firing)
{
yield return new WaitForSeconds(timeBetweenShots);
Fire();
}
}
private void Fire()
{
GameObject enemyLazer = Instantiate(enemyLazerPrefab, transform.position, transform.rotation);
enemyLazer.GetComponent<Rigidbody2D>().AddRelativeForce(Vector2.up * projectileSpeed, ForceMode2D.Impulse);
}
} It is working just fine if the y-axis of the player does not align the child's y-axis. However, if does align, the child's x rotation somehow becomes -180 and the projectile that is instantiated starts firing in the opposite direction as shown here
Somehow despite the line of code that adds force in the direction of the projectile's positive y-axis, the projectile is moving with a velocity of +5(upwards) while its vector2.up is pointing downwards towards the player.
Please help me if you can.
Thanks for reading(This is my first post so if i happen to make any mistake please feel free to correct me.)