Move a Game Object within a radius of another Game Object (2d)
Hello!
I am working in a 2d environment. My basic idea is to have two game objects - a "Character" and an "Orbit." You move the Character around the screen by dragging with the left mouse button. If you click and drag away from the Character object with the right mouse button, you summon and move the Orbit object as it follows your mouse. When you release the right mouse button, the Orbit de-spawns.
That is what I have so far.
What I would like to do now is make it so that there is a maximum distance "r" away from the Character that the Orbit can be dragged. If you drag further, the Orbit continues to slide along the edge of the r-boundary, even as you continue dragging.
I figured the trick would have to do with raycasting. Something like casting a ray from the Character to the tip of the mouse, and transforming the Orbit's position to be at the endpoint of the ray, with a maximum distance along the ray allowed. Am I going in the right direction or am I way off-base?
Thanks!
Here is the code I have working. At the moment it simply drags the two objects using left-and-right-click. This script is affixed to the Character object, with an orbit prefab ready-to-go.
public class moveCharacter : MonoBehaviour
{
private bool canAttack = true;
public GameObject orbPrefab;
GameObject orbitObject;
private void OnMouseDrag()
{
Vector2 mousePos = Input.mousePosition;
Vector2 charWantedPos = Camera.main.ScreenToWorldPoint(new Vector2(mousePos.x, mousePos.y));
transform.position = charWantedPos;
}
private void OnMouseOver()
{
if (Input.GetMouseButton(1) && canAttack)
{
canAttack = false;
orbitObject = Instantiate(orbPrefab, transform.position, UnityEngine.Quaternion.identity);
}
}
private void Update()
{
if (Input.GetMouseButtonUp(1))
{
Destroy(orbitObject);
canAttack = true;
}
if (Input.GetMouseButton(1))
{
Vector2 mousePos = Input.mousePosition;
Vector2 orbWantedPos = Camera.main.ScreenToWorldPoint(new Vector2(mousePos.x, mousePos.y));
orbitObject.transform.position = orbWantedPos;
}
}
}
Your answer
Follow this Question
Related Questions
Help Converting Raycast Into a Raycast2D 0 Answers
Raycast2D don't hit anything below 0 Answers
Raycast is hitting enemy even when not in contact with it? 2 Answers
Rigidbody blocking raycasts 2D 0 Answers
CircleCast hit its origin... 0 Answers