Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Rotate a gameobject so that it faces another

Discussion in '2D' started by Gonzasmpl, Apr 20, 2019.

  1. Gonzasmpl

    Gonzasmpl

    Joined:
    Jul 30, 2018
    Posts:
    55
    Hi, I can not figure out how to rotate the gun in order to make the gun cannon "aims" or faces the blue dot in the image (That blue dot represents the cursor). The rotation point of the gun is A, it is there because there is a hand that holds the gun and the gun should rotate in relation the hand. Right now the gun rotates so that the point A (rotation point) is always aligned with the blue dot, but I can't manage to make the shooting point (which is point B) "faces" the blue dot.

    I need the cannon of the gun aims to the blue dot because the pistol shoot a bullet from point B and forward depending on the rotation of the gun.

    If you think of a way to rotate the gun in order to have point B and the blue dot aligned so that the gun could shoot with precision and dont shoot with this "offset" it has right now let me know.
    Thanks!
    RotationHelp.png
     
  2. beanie4now

    beanie4now

    Joined:
    Apr 22, 2018
    Posts:
    311
    Code (CSharp):
    1. var dir = Input.mousePosition - Camera.main.WorldToScreenPoint(transform.position);
    2.             var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
    3.             transform.rotation = Quaternion.AngleAxis(angle - 90, Vector3.forward);
     
  3. Gonzasmpl

    Gonzasmpl

    Joined:
    Jul 30, 2018
    Posts:
    55
    It works nice, thanks!