I'm trying to implement a bow in my game that follows the direction of my mouse. There are many tutorials also showing how it is done and they are all quite the same.
The issue is that the cursor has to rotate around a center which is not the game object. It is better visible in video: https://streamable.com/iyhz87
I'm sure that my game object is actually not moved down to where the cursor is.
This is the code I am using:
void FixedUpdate()
{
Vector2 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
float rotZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0, 0, rotZ + offset);
}
Your rotation or lookat code for the bow is working perfect, what u might be facing is some sort of offset error, try setting the position of the bow transform some units above to fix the pivot at the centre of the sprite.. to be exact the offset would be something like, Vector3(0,spriteHeight/2,0); and add it to wherever you are making the bow transform follow the player transform..
or if the bow is child of the player try this code and see:
void Start(){
offsetY = GetComponent<SpriteRenderer>().sprite.rect.height / 2;
this.transform.localPosition = new Vector3(0,offsetY,0);
}
void FixedUpdate()
{
Vector2 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
float rotZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0, 0, rotZ + offset);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With