Continuously moving an object around on a surface

Hi All

I’m trying to do something fairly simple but i’m getting unexpected (illogical?) results.

Basically I just want to hold down the mouse button and have an object follow the mouse cursor as it passes over an object.

So the object will snap down to the object surface and move around it, as long as the mouse button is held down.

Here’s my code:

var OriginObj : GameObject;
var MainCamera : Camera;

function Update () {

var MouseDown = 	Input.GetMouseButton(0);

	if (MouseDown)
	{
		var OriginRay : Ray = MainCamera.ScreenPointToRay (Input.mousePosition);
		var OriginRayHit : RaycastHit;
		if (Physics.Raycast (OriginRay, OriginRayHit, Mathf.Infinity)) {	
			OriginObj.transform.position = OriginRayHit.point;
			}
	}
}

Now reading through the code, everything should work fine. But… instead, what happens is:

It places the object on the surface correctly, but whenever the mouse is still (not moving), the object begins to fly straight towards the camera.

If I move the mouse, it snaps the object back to the surface. So if I am continuously moving the mouse, the script works as intended. But as soon as I stop moving the mouse (with the button still held down), the object flies up and towards the camera.

It’s got me stumped… any ideas?

the raycast is hitting the cube you just placed which makes the cube get closer each time.

Either take collider off the cube, or test what the raycast is hitting.

Haha, I can’t believe it…such a simple thing. Thanks very much for the quick reply, I really appreciate it!

no worries :slight_smile: Glad I could help.