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

Cursor rotating around player

Discussion in '2D' started by ReeceHunter, Apr 30, 2020.

  1. ReeceHunter

    ReeceHunter

    Joined:
    Jan 20, 2014
    Posts:
    2
    In my game, I have my cursor orbit around the player in a circle, instead of being free. This works really well, but I want the cursor to act the same way with a joystick. How can I make this code also work with the joystick?

    Here is a link to a GIF showing what I mean: https://imgur.com/kTg7qiI

    Code (CSharp):
    1. private void Start()
    2.     {
    3.         target = GameObject.FindGameObjectWithTag("Player").transform;
    4.  
    5.         Cursor.visible = false;
    6.         Cursor.lockState = CursorLockMode.Confined;
    7.     }
    8.  
    9.     private void Update()
    10.     {
    11.         Vector3 targetScreenPos = Camera.main.WorldToScreenPoint(target.position);
    12.         targetScreenPos.z = 0;
    13.         Vector3 targetToMouseDir = Input.mousePosition - targetScreenPos;
    14.  
    15.         Vector3 targetToMe = transform.position - target.position;
    16.         targetToMe.z = 0;
    17.  
    18.         Vector3 newTargetToMe = Vector3.RotateTowards(targetToMe, targetToMouseDir, 3, 0f);
    19.  
    20.         transform.position = target.position + 3 *newTargetToMe.normalized;
    21.     }
     
  2. nabrown

    nabrown

    Joined:
    Jun 27, 2019
    Posts:
    27
    Seems like a joystick would be easy:

    Vector2 joystickVector = Vector2.clampMagnitude(new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")), 1.0f);
    Vector2 offset = joystickVector * cursorOffsetDistance;
    transform.position = target.position + offset;

    Didn't test this, so forgive me for any mistakes but I think the general idea should work.