Strange behavior when using rays

I’ve been trying to get my platform game object to follow my mouse’s position via rays. Problem is, however, the z coordinate for my platform is constantly changing, even when the mouse is completely stationary, making it impossible to control the platform. I’m guessing that there is a way to keep the z coordinate from changing, but I do not have the scripting knowledge to do so.

using UnityEngine;
using System.Collections;

public class PlatformSpawning : MonoBehaviour {
	Ray ray;
	RaycastHit hit;
	public GameObject platform;
	public GameObject region;


	void Update () {

		ray = Camera.main.ScreenPointToRay (Input.mousePosition);

		if (Physics.Raycast (ray, out hit)) {


			if (hit.transform.name == "region" || hit.transform.name == "Platform") {
				platform.transform.position = hit.point;
			}
		}
	}
}

Well, since you move your platforms origin to the hitpoint you most likely will hit the platform itself so the hit point is closer to the camera since it’s on the surface of the platform and not at the depth of the origin of the platform.

Since you execute this code every frame and you move the platform every frame that could result in such a behaviour you’re describing. You haven’t said if you have a 2d or 3d setup and if you use a perspective or orthographic camera.

It’s not really clear what your desired behaviour is. The platform probably should be moved on some kind of plane which is parallel to the viewport. However from the bit of code you’ve posted we can’t really derive how you use this script.

if (hit.transform.name == “region” || hit.transform.name == “Platform”) {
Vector3 pos = hit.point;
pos.z = 0; //or whatever you want
platform.transform.position = pos;
}