- Home /
How to make the object stop moving within a certain distance with the target.
My first post here and I have a problem, (as well as some other generic questions.)
OK so, I have made a script for making an object move towards a position that I click on with my mouse. Problem here is, when my object hits the location specified, it does not stop, but rather spins around non-stop in a tight circle around the location. My question is how do I get this thing to stop?
Also if anyone can tell me how to calculate the distance between my object and the position I clicked on, that would be amazing.
Also, Input.mousePosition gives me the co ordinate on my screen of where my mouse is, is there a way to easily convert the point to a transform.position in the world?
Note: this code is basically a noob's "Grumping" of this one http://www.unifycommunity.com/wiki/index.php?title=LookAtMouse #pragma strict
var moveOrders:Vector3;
var speed = 2.0;
function Update ()
{
	
	var playerPlane = new Plane (Vector3.up, transform.position);
	
	
	if (Input.GetKey (KeyCode.Mouse1))
	{
		
	moveOrders= Input.mousePosition;
	
	
	}
	Debug.Log (moveOrders);
	var ray = Camera.main.ScreenPointToRay (moveOrders);
	var hitdist = 0.0;
	if (moveOrders != Vector3 (0.0,0.0,0.0))
	{
		if (playerPlane.Raycast (ray, hitdist))
		{
			var targetPoint = ray.GetPoint(hitdist);
			
			var targetRotation = Quaternion.LookRotation (targetPoint - transform.position);
			 transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, speed * Time.deltaTime);
			
			 transform.position += transform.forward * speed * Time.deltaTime;
			if (transform.position== moveOrders)
				{
					moveOrders= Vector3(0,0,0);
				}
			}
		if (transform.position- moveOrders == Vector3.zero)
		{
			moveOrders= Vector3(0,0,0);
		}
	}
}
Answer by whydoidoit · Oct 06, 2012 at 07:43 PM
So the position you clicked on in the world -
This can be kind of tricky - you can use Camera.main.ScreenToWorldPoint but you have to specify at what Z distance you are clicking. So you probably have some kind of ground that you want to click on? If you do you can cast a ray from the camera, through the screen point and use the place it hits your ground. Fastest way to do that is to use the collider attached to your ground and do a collider based Raycast - the example in that link shows doing it with a screen position. The resulting RaycastHit contains a .point variable which is the point on the collider that was clicked on.
To measure the distance just use Vector3.Distance passing the two positions.
Clearly stopping your thing is a matter of measuring the distance and stopping if it is < some value (don't do == 0, it's not accurate enough).
Your answer
![](https://koobas.hobune.stream/wayback/20220613081954im_/https://answers.unity.com/themes/thub/images/avi.jpg)