- Home /
Click Point From Raycasting Not Yielding Expected Coordinates
I'm working on a board game and have a textured rectangular solid thats 918 x 50 x 550, where 918 is the width of the board and 550 is the height. The board's texture is a 918 x 550 BMP. Then the main camera is looking down at a 63 degree angle. On update, I'm running a raycast to get the mouse click position and translating it to the texture coords:
private RaycastHit GetRaycast(Vector3 position) { Camera clickCamera = Camera.main;
if(clickCamera == null)
return default(RaycastHit);
RaycastHit hit;
Ray ray = clickCamera.ScreenPointToRay(position);
if (!Physics.Raycast(ray, out hit))
return default(RaycastHit);
Renderer renderer = hit.collider.renderer;
MeshCollider meshCollider = hit.collider as MeshCollider;
if (renderer == null || renderer.sharedMaterial == null ||
renderer.sharedMaterial.mainTexture == null || meshCollider == null)
return default(RaycastHit);
return hit;
}
private Vector2 GetHitCoordinatesOnObject(RaycastHit hit) { var pixelUV = hit.textureCoord; Texture2D tex = hit.collider.renderer.material.mainTexture as Texture2D;
pixelUV.x *= tex.width;
pixelUV.y *= tex.height;
Debug.Log("clicked (" + pixelUV.x + "," + pixelUV.y + ")");
return pixelUV;
}
However my debug message is displaying a range ~0 to ~1020 for the width and ~0 to ~510 on the height. This is throwing me off when I try to map the click to world coordinates. Can someone explain to me what's happening here and how I'm supposed to fix it?
Thank you very much!
Answer by Jessy · Feb 19, 2011 at 06:17 PM
I'm not sure I understand this completely, but I think what you're saying is that you expect values between 918 and 550 instead of 1024 to 512. A compressed texture has to be in powers of two. I figure your solution would be to not multiply by the dimensions of the texture, but rather, the values you actually want to use. Let me know if I'm off on this.
But I don't see why you need to use the UVs, anyway.
Because I have no clue what I'm doing with this. haha :) Different recommendations are more than welcome. This is my first Unity project. Thank you for you answer.
Yea, most of that code was from an example I found on the Unify wiki. I've modified it and am now using RaycastHit.point. Definitely a more elegant solution than the other. Thanks for your help.
It seems to me that RaycastHit.point should work fine, and yield the same numbers you were going for with your textureCoord method. Did you have issues with it that caused you to switch the data checked?
Your answer
Follow this Question
Related Questions
Use raycast to click on object 3 Answers
question about instantiating 2 Answers
How to destroy specific gameobject with a mouse click once player is looking at them using a Ray 1 Answer
I am stuck and don't know what to do, After upgrading to 2019 mouse and raycast don't work well 1 Answer
How to create gameobjects by clicking in the scene view in the editor? 1 Answer