- Home /
Cannot get game object to correctly follow mouse
What I'm tying to achieve is a game object to accurately follow my cursor, I just can't figure it out.
What I have.
using UnityEngine;
using System.Collections;
public class HandCursor : MonoBehaviour {
public Vector3 moose;
public float baseX = 0.0f;
public float baseY = 0.0f;
public float sensX = 1.0f;
public float sensY = 10.0f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update ()
{
if(Input.GetAxis("Mouse X") < 0)
{
transform.Translate(-sensX, 0, 0 * Time.deltaTime);
}
if(Input.GetAxis("Mouse X") > 0)
{
transform.Translate(sensX, 0, 0 * Time.deltaTime);
}
if(Input.GetAxis("Mouse Y") > 0)
{
transform.Translate(0, 0, sensY * Time.deltaTime);
}
if(Input.GetAxis("Mouse Y") < 0)
{
transform.Translate(0, 0, -sensY * Time.deltaTime);
}
}
}
What it looks like, pardon the audio I had a stream in the background.
Answer by razveck · Mar 07, 2015 at 11:52 PM
What's happening is that the mouse pointer moves in screen space (X by Y pixels), and those units don't translate linearly to world space. So you need a raycast.
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition); //creates a ray from the camera into the world
RaycastHit hit;
if (Physics.Raycast (ray,out hit)) {
transform.position+=(hit.point-transform.position).normalized*Time.deltaTime;
}
Answer by KurtGokhan · Mar 07, 2015 at 11:58 PM
You are moving the object according to mouse movement delta. Instead you should place the object right where the mouse is. You can do this by casting a ray from mouse position as if it is coming out of camera and place the object where the ray and the plane you are placing your object intersects. The code would be like:
// This represents the xz plane, you can change this to your needs
Plane groundPlane = new Plane(Vector3.up, Vector3.zero);
static public void MouseGamePosition(){
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
float rayDistance;
if (groundPlane.Raycast(ray, out rayDistance))
transform.position = ray.GetPoint(rayDistance);
}
More on planes: Plane