- Home /
Why arrow instantiating in wrong direction in range attack?
hi there, hope you are in good health.
I am implementing a ranged attack it is working fine when the character is moving towards the right, but the arrow is instantiating in the same direction (arrow goes back from the bow) when the character moves towards the left. Which I don't want.
I need help anyone please help me out with this. here snapshots of the game view and code.
public class Bow: MonoBehaviour {
public float offset;
public Transform shotPoint;
public GameObject projectile;
public float timeBtwShots;
public float startTimeBtwShots;
void Update()
{
Vector3 bowPosition = transform.position;
Vector3 difference = Camera.main.WorldToScreenPoint(Input.mousePosition) - transform.position;
float rotZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rotZ + offset);
Debug.Log("" + rotZ + offset);
if (Input.GetMouseButtonDown(0))
{
Instantiate(projectile, shotPoint.position, transform.rotation);
}
}
}
Answer by SamyBoyJim · Oct 07, 2021 at 06:38 AM
Hi there!
A. I think you should put all of vector calculating logic in the if statement so you aren't having to calculate that every frame and only when you click the mouse button. The bowPosition variable also seems useless, I haven't seen the whole script but don't reference it if you don't have to. These fixes are not super important but it is always good to improve performance when you can!
B. You haven't supplied much information that I can make sense of in your post but from what I can make sense of, you want to fire the arrow towards the mouse pointer. This code is correct and is doing what it is meant to do except for the offset value; I have worked with atan2 in situations like this before and i believe the perfect offset is -90 so I think if add that then it will work but can you clarify what the problem is because it wasn't clear in your post what the problem was?
Hope this helps!
Answer by zahidashahid535 · Oct 07, 2021 at 07:33 AM
Thanks for your answer,
The problem was with the prefab it was not flipping when the player moves in the left direction. now it is working fine.
but a new issue was raised while fixed this.
an arrow (instantiated) shot in the right direction, but at that moment when the player changes its direction previously shot or instantiated arrows came back towards the point of the shoot. it's due to the script attack to prefab. value changes also on previously instantiated arrows.
Would help me with this. If you are getting my point.
Your answer
![](https://koobas.hobune.stream/wayback/20220613043923im_/https://answers.unity.com/themes/thub/images/avi.jpg)