Hey! How could I make it so that a gameobject position is max 10f units from origin position towards mousposition?
Example:
Origin is at Vector3(0,0,0).
Mouse position is somewhere in the outer circle 25f units away from the origin. (Or any distance > 10f)
I want the function to calculate the gameobject position between the origin and mouse position, and set the max distance to be 10f units(so that the gameobject can be placed anywhere around 10f unit radius around the origin).
// given this...
Vector3 origin = ...
Vector3 mouseInWorldPosition = ...
float maxDistance = 10.0f;
//compute offset:
Vector3 offset = mouseInWorldPosition - origin;
// is it to far? do we need to clamp?
if (offset.magnitude > maxDistance)
{
// norm
offset.Normalize();
// scale to your intended radius
offset *= maxDistance;
}
Vector3 limitedPosition = origin + offset;
// now use limitedPosition to move your Transform...
if (Physics.Raycast(ray, out hit, Mathf.Infinity, groundLayer))
gameObject.transform.position += Vector3.ClampMagnitude(hit.point-gameObject.transform.position, 10);
Samana seems to have done a typo. I think he was going for something like this:
if (Physics.Raycast(ray, out hit, Mathf.Infinity, groundLayer))
transform.position=origin.position+Vector3.ClampMagnitude(hit.point-origin.position,10);
Although if the origin is always zero then you can just do this:
if (Physics.Raycast(ray, out hit, Mathf.Infinity, groundLayer))
transform.position=Vector3.ClampMagnitude(hit.point,10);
Yes, perhaps I made a mistake by taking the player’s position as the reference point instead of the origin. I somehow missed this nuance and thought that the origin was just for describing the example task.
That’s what happens when you become experienced. To save energy you start relying more on intuition rather than thinking everything through methodically. But you obviously had the right idea and you would’ve spotted and corrected your mistake instantly after hitting the Play button. I do it all the time!
@samana1407 & @zulo3d thank you! I tried samanas method and realized that something is weird and couldn’t figure it out until zulos’s reply. This works like charm I’m sure Kurt’s method would work also but this seemed simpler