Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
2 captures
12 Jun 22 - 14 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
10
Question by CarterG81 · Feb 06, 2017 at 03:05 PM · movementspherelimitcircleboundary

How to keep an object within a circle/sphere (radius) - NO RECTANGLE

To limit movement in a rectangle, it is easy

         if (newLocation.x > maxPosition)
         {
             newLocation.x = maxPosition;
         }
         else if (newLocation.x < -maxPosition)
         {
             newLocation.x = -maxPosition;
         }

         if (newLocation.z > maxPosition)
         {
             newLocation.z = maxPosition;
         }
         else if (newLocation.z < -maxPosition)
         {
             newLocation.z = -maxPosition;
         }

However, whenever you want to keep these boundaries in a CIRCLE, rather than a RECTANGLE, it becomes mathematically complex (for those like me who haven't taken a math course in over a decade).

How do I limit movement in a circle, rather than a rectangle? Unity's functions don't see to help. I even tried complex things like using a SphereCollider and ClosestPointOnBounds (which returns for a rectangle...even when used with a SphereCollider)

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

3 Replies

· Add your reply
  • Sort: 
avatar image
25
Best Answer

Answer by CarterG81 · Feb 06, 2017 at 03:14 PM

Alt text

 float radius = 400; //radius of *black circle*
 Vector3 centerPosition = transform.localPosition; //center of *black circle*
 float distance = Vector3.Distance(newLocation, centerPosition); //distance from ~green object~ to *black circle*
 
 if (distance > radius) //If the distance is less than the radius, it is already within the circle.
 {
 Vector3 fromOriginToObject = newLocation - centerPosition; //~GreenPosition~ - *BlackCenter*
 fromOriginToObject *= radius / distance; //Multiply by radius //Divide by Distance
 newLocation = centerPosition + fromOriginToObject; //*BlackCenter* + all that Math
 }

If the distance is < radius, it is within the circle. No need for any calculations. If the distance is > radius, the object is outside the circle.

  1. Determine the center position of the circle/radius. The radius of this circle is also the maximum limit.

  2. Determine the distance between point A (circle/bounds) and B (object you want to limit; prevent movement outside of bounds A).

  3. If the distance is greater than the radius, then do the following:

  4. Get Vector3 U from B (object) minus A (circle). (U = B - A)

  5. Multiply by Radius (U x Radius)

  6. Divide by Distance (U / Distance)

  7. Position = U + A (maxLocation = U + A)

Comment
Add comment · Show 5 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image SheZii · Feb 05, 2019 at 03:08 PM 0
Share

Like a charm (y)

avatar image Edisyo · Aug 20, 2019 at 01:07 PM 1
Share

Thanks so much!

Only one thing, at least for me, I needed to add

 newLocation = centerPosition + fromOriginToObject; //*BlackCenter* + all that $$anonymous$$ath
 
 //ADDED CODE
 transform.position = newLocation; 


I use mouse position to update green objects position. At first this didnt work, but I looked at logs and figured out I need to put void, that gets the mouse Input, in Update, not LateUpdate (I red that it needs to be in LateUpdate). Worked perfectly after that!

avatar image Niborsom Edisyo · Apr 21, 2020 at 09:32 AM 0
Share

I've been struggling with this for a long time in unity 3d. With the help from CarterG81 and Edisyo (thanks!) I got the following code:

 public Transform player; // get the player transform, or w/e object you want to limit in a circle
 public Vector3 circleCenter; // this is a location that is set to the middle of my world, it will be the center of your circle.
 
 Void Update()
 {
         float radius 20f; // this is the range you want the player to move without restriction
         float dist = Vector3.Distance(player.position, circleCenter); // the distance from player current position to the circleCenter
         
         if (dist > radius)
         {
             Vector3 fromOrigintoObject = player.position - circleCenter;
             fromOrigintoObject *= radius / dist;
             player.position = circleCenter + fromOrigintoObject;
             transform.position = player.position;
         }
 }

}

avatar image tatecreative · Dec 04, 2020 at 05:10 PM 0
Share

Any chance we can get a working example of this? Like what if I wanted to place the object in a random position within this circle?

avatar image shaaafeee tatecreative · Dec 06, 2020 at 10:42 AM 0
Share

You can instantiate the object/objects from a random position inside the circle, with Random.Range

avatar image
15

Answer by Bunny83 · Feb 06, 2017 at 03:15 PM

Well, don't use max / min positions as they define a rectangle. What you want is defining a center point and a radius. Then just use Vector3.ClampMagnitude on the relative vector:

 // C#
 Vector3 v = newLocation - circleCenter;
 v = Vector3.ClampMagnitude(v, circleRadius);
 newLocation = circleCenter + v;

If the circle center and your location is not on the same "height" (y value) you can do:

 // C#
 circleCenter.y = newLocation.y;
 Vector3 v = newLocation - circleCenter;
 v = Vector3.ClampMagnitude(v, circleRadius);
 newLocation = circleCenter + v;


Comment
Add comment · Show 3 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image CarterG81 · Feb 06, 2017 at 03:21 PM 0
Share

Thank you. Your answer was so incredibly quick, I wasn't able to put my own in fast enough. I was trying to document this for others, because I found this question difficult to answer but finally found an answer myself.

I apologize for this. Thank you for this alternative.

avatar image Br00dl0rd · Aug 20, 2020 at 07:56 PM 0
Share

Thank you! You just mentioning Vector3.Clamp$$anonymous$$agnitude helped me so much, I managed to fix my issue!

avatar image Coulomb1 · Jul 14, 2021 at 03:21 AM 0
Share

So short and efficient! Thank you so much!

avatar image
1

Answer by grizzly48 · Feb 07, 2017 at 01:33 PM

Hi, I would simply check the distance. I´m correct in the assumption, that we´re in the two-dimensional-space?

 Vector2 center;
 Vector2 position;
 float maxDistance;
 
 float actualDistance = Vector2.Distance(center, position);
 
 if (actualDistance > maxDistance)
 {
     Vector2 centerToPosition = position - center;
     centerToPosition.Normalize();
     position = center + centerToPosition * maxDistance;
 }

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image CarterG81 · Feb 09, 2017 at 07:31 PM 0
Share

I actually use this for 2D game in a 3D game world. It was to "build structures" in the game; a form of crafting or equivalent of a RTS game where you move your mouse around to place buildings down at specific coordinates.

It works fine in a 3D world, if you are able to handle your Y-Axis ($$anonymous$$e was always 0, so no problem here).

I initially needed to convert $$anonymous$$ouse Coordinates into 3D world coordinates. However Unity's conversion of $$anonymous$$ouse to World coordinates was very jittery. ($$anonymous$$oving the mouse wouldn't necessarily move the world coordinates, resulting in huge jumps in world coordinates, no matter what method I tried, including raycasting).

So I ended up just attaching an object to the player, and then attaching a sprite (of what the player is trying to build) to that object (what is in essence a gameobject that acts as a mouse cursor, but for joystick controllers). This "cursor gameobject" moves in the X/Z axis in 3D world space, based on the code I posted.

Eventually I will figure out how to get smooth mouse to world coordinate conversion, and then simply (if not a controller/joystick) move said "cursor gameobject" based on mouse coordinates.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

94 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

keep object inside circle 1 Answer

set limit mouse x y Help needed 1 Answer

Boundaries / movement constraints 7 Answers

How to limit Cannon shooting for certain range in unity 2d ? 0 Answers

Moving an ob around a sphere 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges