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. Dismiss Notice

Help with some code (mouse directional targeting)

Discussion in 'Scripting' started by jeffd5, Mar 28, 2018.

  1. jeffd5

    jeffd5

    Joined:
    Mar 13, 2018
    Posts:
    4
    SO im trying to have a target follow a mouse around my player
    Similar to this:

    i even tried to copy his code, my issue is i cannot get the target to rotate around the player, its sorta stuck rotating somewhere else and then when i move my player the target starts to move across the screen really fast.

    my code:
    Code (CSharp):
    1.     private float Radius = .24f;
    2.     private float angle;
    3.     private Vector3 v3pos;
    4.    
    5.     void FixedUpdate () {
    6.         GameObject player = GameObject.Find("Player1");
    7.        
    8.         v3pos = Input.mousePosition;
    9.         v3pos.z = (player.transform.position.z - Camera.main.transform.position.z);
    10.         v3pos = Camera.main.ScreenToWorldPoint(v3pos);
    11.         v3pos = v3pos - player.transform.position;
    12.  
    13.         angle = Mathf.Atan2(v3pos.y, v3pos.x) * Mathf.Rad2Deg;
    14.  
    15.         if (angle < 0.0f) angle += 360.0f;
    16.         transform.localEulerAngles = new Vector3(0,0, angle);
    17.  
    18.         float xpos = Mathf.Cos(Mathf.Deg2Rad * angle) * Radius;
    19.         float ypos = Mathf.Sin(Mathf.Deg2Rad * angle) * Radius;
    20.  
    21.         transform.localPosition = new Vector3(player.transform.position.x + xpos * 2, player.transform.position.y + ypos * 2, 0);
    22.  
    23.     }
     
  2. jeffd5

    jeffd5

    Joined:
    Mar 13, 2018
    Posts:
    4
    I figured it out just now, it was the final tranform.localposition i changed it to transform.position and now it works.

    EDIT: well it sorta works, it ever so slightly moves the target a little off while my character is moving, its barely noticeable tho.