- Home /
Can't make object follow mouse cursor position.
I am trying to get this object to move with the cursor on a 2D axis. (It's the red cross hairs). This is the C# script I made for it:
using UnityEngine;
using System.Collections;
public class Player_Curser_Movement : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Vector3 temp = Input.mousePosition;
temp.z = 5f;
transform.position = temp;
}
}
I had it print out the x, y, and z coordinates of the object, when my cursor was over the center, it said the coordinates were around: 436, 244, 5. When my mouse is in the bottom left corner of my screen it puts the object around the middle of the screen, but it's very sensitive to movement.
This may help http://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html
You have to convert from screen to world cords.
Answer by Ali-hatem · Apr 01, 2016 at 08:31 AM
any input on the screen is defined by pixels & object in unity move by points so if the screen width is 800 then the middle will be 400 so you are sending the object 400 point away where if you see by your self the screen width is sometimes 4 or 6 or whatever so as @markpollard1 said you have to convert the input click or touch from pixels to points .
void Update () {
Vector3 temp = Camera.main.ScreenToWorldPoint(Input.mousePosition);
temp.z = 5f;
transform.position = temp;
}
Your answer
Follow this Question
Related Questions
Lookat player 2 Answers
Distribute terrain in zones 3 Answers
How to make LineRenderer in GameObject Facing? 1 Answer
How do I make my enemy have animations for directions during movemvent 1 Answer
2D Topdown Shooter Enemy Knockback 0 Answers