Lock object distance to the main object
So, this is something simple and yet haven't been able to find a way to solve it, I'm quite new on this. I want my object to follow the mouse cursor, for which I used this:
void Update () {
Vector3 follow = Camera.main.ScreenToWorldPoint(Input.mousePosition);
follow.z = 5f;
transform.position = follow;
}
But while it does, I want this smaller object movement to be restricted around a bigger object (Example: like a moon orbiting a planet) so when you move the mouse, it will simple rotate around this main object.
I mean I can simply do this:
Vector3 allowedPos = follow - theCenter;
allowedPos = Vector3.ClampMagnitude(allowedPos, 130.0f);
transform.position = theCenter+ allowedPos;
but that would restrict the movement to a fixed radius, and I want it to be able to move further or closer to the main object, within a certain range. Is that possible?
Answer by SneakyLeprechaun · Aug 21, 2017 at 02:28 AM
Something like this?
public Transform ConstrainToZ; public float Radius; void Update () { Vector3 follow = Camera.main.ScreenToWorldPoint(Input.mousePosition); follow = new Vector3(follow.x - ConstrainToZ.position.x, follow.y - ConstrainToZ.position.y, ConstrainToZ.position.z); follow = follow.normalized * Radius; transform.position = ConstrainToZ.position + follow; }
by subtracting the position of the object you want to rotate around and then normalizing the vector, you get the direction relative to the bigger object. Then by multiplying it by a radius you constrain it to that distance from your desired object.
Well, that indeed does the trick to have a fixed rotation around the object, but I have a question, you think it is possible to set max and $$anonymous$$ values to the radius, so the smaller object can move closer or further to the main object within that radius?
Yeah, I think so. I haven't tested this, but try it:
ins$$anonymous$$d of setting follow to follow.normalized * Radius, set it it to
follow.normalized * $$anonymous$$athf.Clamp(follow.magnitude,0,Radius);
and it should limit it.
Works like a charm! thank you very much!
Your answer
Follow this Question
Related Questions
Use Quaternion.lookat to rotate On One Axis (for turret.) 1 Answer
help ordering array for planetary gravity 1 Answer
Move player distance forward over time. 0 Answers
Spawn a number of prefabs an equal distance apart 2 Answers
Adding some offset value for RayCast 2D but what is the distance unit? 0 Answers