I’m trying to add a simple little system that shoots projectiles to the mouses location on click. I’ve it added and it’s shooting projectiles like I want it to, just not at the right direction. It doesn’t matter where my mouse is, if my character is on the right side of the scene, the projectiles will shoot left and if it’s on the left side, you guessed it - projectiles will fire away to the right.
Any idea what could be causing this? Here’s the relevant function.
Declare public float angleOffsetInDegrees, change it in the inspector to get the desired rotation in degrees.
void Shoot() {
if (Input.GetMouseButtonDown(0)) {
Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition); //Mouse position to world position
Vector2 myPos = new Vector2(transform.position.x, transform.position.y);
//Calculate direction in quaternion
Quaternion targetQuaternion = Quaternion.Euler(Quaternion.LookRotation(Vector3.forward, mousePos - myPos).eulerAngles + new Vector3(0f, 0f, angleOffsetInDegrees));
//Calculate direction in Vec3
Vector3 direction = new Vector3(Mathf.Sin(-targetQuaternion.eulerAngles.z * Mathf.Deg2Rad), Mathf.Cos(targetQuaternion.eulerAngles.z * Mathf.Deg2Rad), 0f);
direction.Normalize();
//Instantiate
GameObject projectile = (GameObject)Instantiate(projectilePrefab, firePoint.position, targetQuaternion);
projectile.GetComponent<Rigidbody2D>().velocity = direction * speed;
}
}
First I calculate the Quaternion setting the foward vector as the pivot for the rotation, and then the Vector3 using the Sin and Cos functions to get the corresponding angle.