Search Unity

[Please Help] 2D keeping an object within a fixed radius from main object

Discussion in '2D' started by ClownOfMadness, Feb 16, 2020.

  1. ClownOfMadness

    ClownOfMadness

    Joined:
    May 25, 2018
    Posts:
    4
    Hello.

    Im trying to make a certain sprite to follow mouse position but stay within a fixed radius from the main player sprite, so it will look like it only circles around the player. i need to only lock the distance of from another without touching rotation of the object as i need them to stay in the same rotation. the game isn't a clean 2D axis game, I am using the z and x axis.

    Thank you in advance!
     
  2. ClownOfMadness

    ClownOfMadness

    Joined:
    May 25, 2018
    Posts:
    4
    Code (CSharp):
    1. void StepRotateMovement()
    2.     {
    3.         lockedDistance = Vector3.Distance(shadow.transform.position, transform.position);
    4.  
    5.         shadow.transform.position = convertedMousePosition;
    6.  
    7.         if (lockedDistance != 3f)
    8.         {
    9.             Vector3 fromOriginToObject = shadow.transform.position - transform.position;
    10.             fromOriginToObject *= 3f / lockedDistance;
    11.             shadow.transform.position = transform.position + fromOriginToObject;
    12.         }
    13.     }
    this is what I tried doing but as of result i am getting the shadow object to glitch infinitely between the center and its new position. besides that it doesn't lock its distance and instead it only reduces it.
     
  3. PuppyPolice

    PuppyPolice

    Joined:
    Oct 27, 2017
    Posts:
    116
    I think can tell you the reason it flickers its due to you setting shadows position at line 5 and then switches it again at line 11 causing it to switch from position to position. You can add an else statement to the if statement and move line 5 to the else block and it should fix the flicker, I think