- Home /
Getting Transform position using mouse position
I am trying to display the Transform position of a GameObject. When the mouse click on any part of the GameObject, it will display the current Transform position that the mouse position is currently at. If it is possible please show me how the code works.
Answer by getyour411 · Sep 06, 2013 at 02:40 AM
Look at the doc for further information about Input.mousePosition and Raycast (C#). You want something like this:
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Physics.Raycast (ray, out hit);
hit.transform is your GameObject transform
Answer by Ozcorps · Sep 06, 2013 at 02:43 AM
This is what your looking for, this is the best way ive found from searching and seeing it in tutorials.. hope this helps
Camera.ScreenPointToRay
ScreenPointToRay(position: Vector3): Ray;
Description
Returns a ray going from camera through a screen point.
Resulting ray is in world space, starting on the near plane of the camera and going through position's (x,y) pixel coordinates on the screen (position.z is ignored).
Screenspace is defined in pixels. The bottom-left of the screen is (0,0); the right-top is (pixelWidth,pixelHeight).
// Draws a line in the scene view going through a point 200 pixels
// from the lower-left corner of the screen
function Update () {
var ray : Ray = camera.ScreenPointToRay (Vector3(200,200,0));
Debug.DrawRay (ray.origin, ray.direction * 10, Color.yellow);
}
Answer by Hyperion · Sep 06, 2013 at 02:44 AM
For the clicking part, you would want to use
function OnMouseDown () {
}
What do you mean by 'display'?
If you want to find the position of the mouse, you'd have to attach the following to the camera:
static var mousepos : Vector3; //this is going to be the position of the mouse
function Update () //happens every frame
{
var ray = Camera.main.ScreenPointToRay (Input.mousePosition); //making ray point to mouse (invisible)
var hit : RaycastHit;
if (Physics.Raycast (ray, hit,1000))
{
mousepos = hit.point;
}
}
I'll assume by 'display', you mean print. So you'd have to do
function OnMouseDown(0){ //0 means left click
print(mousepos);
}
If this answer helped, please accept it.
Your answer
Follow this Question
Related Questions
[2D] Get the position of an object outside the scope 2 Answers
collider triggers transform position 1 Answer
Trouble converting transform.position to C# 1 Answer
getting the transform.position of a public static Transform? 1 Answer
How do i make my background keep the same position as my character? 0 Answers