Using touch input and raycast to rotate a 2d object. In other words to aim a bow

I have no idea how to do this, I’m still pretty new to c# and unity, and especially unity’s 2d features. I’m trying to make a mobile game and I need to be able to drag my finger up and down to aim a bow. I believe I would use raycast2d to accomplish this, but I don’t really know how to implement it, and I can’t find a tutorial. If you know please educate me or if you know of a tutorial put a link. Thank you.

Try this. What It does is get the mouse position in world coordinates and subtracts the object’s position giving you the direction it is facing. Then you need to get the angle of the direction, and you get the angle axis after that. This way the object will “look at” the mouse pointer. This should be in a script attached to the object you want to rotate in the Update() method, and it assumes that the side pointing towards the mouse is the side of the player pointing towards position X.

This might look confusing at first but if you read up on Atan2 and AngleAxis I promise it will make more sense.

var dir = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
var angle = Mathf.Atan2(dir.y, dir.x)*Mathf.Rad2Deg;
var rot = Quaternion.AngleAxis(angle, Vector3.forward);
transform.rotation = rot;
2 Likes

Thanks this helped a ton. I did some research and I understand it all.

1 Like