how can i limit position between 2 object ??
hello everyone, i am new in unity, i just want make my object[2] can move around object[1], but not to far from object[1], it's just like pict 1, I have searched many solutions on the internet, but not many teach me how to limit position, is there anyone who can teach me. Thanks,, :D
Answer by Hellium · Jan 11, 2018 at 04:20 PM
Here is a very basic joystick script.
Create two images with a circle shaped sprite.
Make the 2nd a child of the 1st one
Attach the following script to the child
Drag & drop the 1st circle (parent) into the
parent
fieldDrag & drop the 2nd circle (child) into the
rectTransform
fieldusing UnityEngine; using UnityEngine.EventSystems; public class Joystick : MonoBehaviour, IBeginDragHandler, IDragHandler { public RectTransform parent; public RectTransform rectTransform; private float radius; Vector2 offset; private void Start() { radius = rectTransform.sizeDelta.x; } public void OnBeginDrag( PointerEventData eventData ) { Vector2 pos; RectTransformUtility.ScreenPointToLocalPointInRectangle( parent, Input.mousePosition, eventData.pressEventCamera, out pos ); offset = rectTransform.anchoredPosition - pos; } public void OnDrag( PointerEventData eventData ) { Vector2 pos; RectTransformUtility.ScreenPointToLocalPointInRectangle( parent, Input.mousePosition, eventData.pressEventCamera, out pos ); Vector2 desiredPosition = pos + offset; if( desiredPosition.sqrMagnitude > radius * radius ) { desiredPosition = desiredPosition.normalized * radius; } rectTransform.anchoredPosition = desiredPosition; } }
INITIAL ANSWER
Your question is not very clear, any existing code would help.
But basically, you can limit the distance between Object2 and Object1 like this :
public void LimitPosition( GameObject gameobject2, GameObject gameobject1, float maxDistance )
{
Vector3 position2 = gameobject2.transform.position;
Vector3 position1 = gameobject1.transform.position;
Vector3 direction = position2 - position1;
float sqrDistance = direction.sqrMagnitude;
if ( sqrDistance > maxDistance * maxDistance )
{
gameobject2.transform.position = direction.normalized * maxDistance + position1;
}
}
thanks for comment, for more details, i want to make my object[2] can move free around object[1], but can not move any further(have a farthest distance limit), just like a joystick, analog can not go away from the background imagelink text
just as the black image is object [2] and the background image is object [1]
I've edited my answer to give you a very basic Joystick script.
Your answer
Follow this Question
Related Questions
There is a way to set a max to the resultant force in a object ? 1 Answer
Why does it matter if I use one GameObject's position or another's when drawing a mesh? 1 Answer
How to prevent the player to move beyond certain x-position value 3 Answers