- Home /
Gameobject follow mouse on center
What needs to happend
The object is instantiated at the mouse position, so that the mouse is centered on the object. Then you can move the object over the terrain while snapping to the grid staying at the Y axis of 1.
What is happening
The cursor isn't calibrated right. It is positioned above the object, not on the center of the object. This causes a really weird placement of the object.
The red circle is where the mouse is positioned right now. The yellow circle is where it should be. (And the cube is the objects that is spawned in, but that is quite obvious I presume)
The code Spawning the object:
public void Spawn(string b) {
var pos = Input.mousePosition;
pos.z = -Camera.main.transform.position.z;
pos = Camera.main.ScreenToWorldPoint(pos);
path = "Objects/" + b + "/" + currentObject;
Debug.Log ("Load path is " + path);
GameObject spawnCurrentObject = Resources.Load(path) as GameObject;
spawnObject = (GameObject)Instantiate(spawnCurrentObject, new Vector3(Mathf.Round (pos.x / gridSize) * gridSize, 50, Mathf.Round (pos.z / gridSize) * gridSize), Quaternion.identity);
}
Moving the object:
void Update () {
var pos = Input.mousePosition;
pos.z = -Camera.main.transform.position.z;
pos = Camera.main.ScreenToWorldPoint(pos);
transform.position = new Vector3(Mathf.Round (pos.x / gridSize) * gridSize, 1, Mathf.Round (pos.z / gridSize) * gridSize);
}
You probably just want to use Camera.ScreenPointToRay and Plane.Raycast, i.e.
void Update () {
Ray ray=Camera.main.ScreenPointToRay(Input.mousePosition);
Plane plane=new Plane(Vector3.up, new Vector3(0, 1, 0));
float distance;
if(plane.Raycast(ray, out distance)) {
transform.position = ray.GetPoint(distance);
}
}
Thank you maccabbe. It's quite odd how I didn't think of using this. Anyhow, I editted your code to my likings (with grid snapping). I will post the full solution and mark is as an answer.
Answer by sandwichmenno · Jun 22, 2015 at 09:09 PM
Credits to maccabbe!!!
float gridSize = 2.0f;
Vector3 points;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Ray ray=Camera.main.ScreenPointToRay(Input.mousePosition);
Plane plane=new Plane(Vector3.up, new Vector3(0, 1, 0));
float distance;
if(plane.Raycast(ray, out distance)) {
points = ray.GetPoint(distance);
}
transform.position = new Vector3(Mathf.Round (points.x / gridSize) * gridSize, 1, Mathf.Round (points.z / gridSize) * gridSize);
}