- Home /
how to make the object position related to the screen
Hi, i don't think this actually a real problem what i want is simple as this, when i do print (Input.mousePosition.x + "-" + myTransform.position.x);
i want the result to be "equal", in other term, i want that the object use the same axes used by the mouse (screen) so if i place the object x,y at 0-0, it will appear in the bottom left of the screen, not in the middle. thanx
Answer by robertbu · Aug 07, 2013 at 05:24 PM
The mouse lives in Screen space that goes from (0,0) in the lower left of the screen and goes to (Screen.width, Screen.height) in the upper right. World space is a 3D environment. In making this conversion, you have to specify the distance in front of the camera. The conversion can be made using Camera.ScreenToWorldPoint().
So if you want the point 10 units in front of the camera:
var pos = Vector3(Input.mousePosition.x, Input.mousePosition.y, 10);
transform.position = Camera.main.ScreenToWorldPoint(pos);
thanx this will make better see things but why do i have a nullReferenceException when i try to do that (copying your code)
If you've changed the tag on your camera, this code will fail. That is the only thing I can see in this code that would cause a Null Reference Exception. If that is not the issue, then I'd have to see your code and a copy and paste of the error.
i don't think my code would help you understand, it has nothing more than these two lines and the basic c# structure, could you please give me a favor and write a method that help me get starting with this ? i want the cube to go where the mouse is clicked in a 2D environment, thank you
Start with a new scene
Create a object like a cube
Add this script to the object
Run the app. The cube will move where you click the mouse.
using UnityEngine;
using System.Collections;
public class ScreenToWorld : $$anonymous$$onoBehaviour {
Camera cam;
void Start () {
if (cam == null)
cam = Camera.main;
}
void Update () {
if (Input.Get$$anonymous$$ouseButtonDown(0)) {
float distance = transform.position.z - cam.transform.position.z;
Vector3 position = new Vector3(Input.mousePosition.x, Input.mousePosition.y, distance);
position = cam.ScreenToWorldPoint(position);
transform.position = position;
}
}
}