Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

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

Discussion in '2D' started by Broddy, Jun 21, 2015.

  1. Broddy

    Broddy

    Joined:
    Jun 21, 2015
    Posts:
    2
    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.
     
  2. jprocha101

    jprocha101

    Joined:
    Apr 8, 2015
    Posts:
    134
    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.

    Code (CSharp):
    1. var dir = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
    2. var angle = Mathf.Atan2(dir.y, dir.x)*Mathf.Rad2Deg;
    3. var rot = Quaternion.AngleAxis(angle, Vector3.forward);
    4. transform.rotation = rot;
     
    theANMATOR2b and Broddy like this.
  3. Broddy

    Broddy

    Joined:
    Jun 21, 2015
    Posts:
    2
    Thanks this helped a ton. I did some research and I understand it all.
     
    jprocha101 likes this.