Search Unity

Question Sprite rotating around a circular object to face the mouse.

Discussion in 'Scripting' started by JustaDuck97, Jul 6, 2020.

  1. JustaDuck97

    JustaDuck97

    Joined:
    Jul 31, 2019
    Posts:
    45
    I'm trying to get and sprite image to rotate around another sprite to face the mouse. The direction being faced will be where the player can shoot from. I've gone through numerous forums and tutorials, but all the available solutions and examples are of an Enter The Gungeon variety. The effect I'm trying to achieve is that similar to an orbiting movement.

    There is an image attached to better describe my meaning. I would greatly appreciate some help because I lack the programming knowledge to figure this out myself. I have been trying for literally days and feel stupid and lost. UnityForumsHelp.png
     
  2. Terraya

    Terraya

    Joined:
    Mar 8, 2018
    Posts:
    646
    Hey there!

    Let me try to understand what you mean and try to help you out! :)

    1 => Parent
    2 => Child (Rotating Object)

    if thats the case, you want the Child Object to rotate towards the mouse, right?

    In that case you will need any type of Script on your Child Object, which rotates towards the mouse point,

    i havent done that in 2D yet but try this:

    Code (CSharp):
    1. void Update()
    2. {
    3.    var dir = Input.mousePosition - Camera.main.WorldToScreenPoint(transform.position);
    4.    var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
    5.    transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
    6. }
    in case that doesnt work, just try to figure out how to rotate an Object in 2D towards the Mouse, shouldnt be so difficult! :)
     
  3. Elango

    Elango

    Joined:
    Jan 27, 2016
    Posts:
    107
    The whole difference of "orbital" rotation is off-centered pivot point. Just set it correctly in Sprite Editor (for sprite) or Rect Transform (for UI Image).
    Examples of rotation code (just in case):