- Home /
CLick on terrain and record vector3 location I clicked at?
I need to click the terrain and know the location which i clicked at in order to tell a unity to go to that location. how do I click the terrain and retrieve at which location I clicked? should I use a raycast and collision or what? HELP!
Answer by Molix · Apr 22, 2010 at 03:15 PM
Use a ray, e.g.
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hit : RaycastHit;
if (Physics.Raycast (ray, hit, 100))
{
Debug.DrawLine (ray.origin, hit.point);
}
Answer by spinaljack · Apr 22, 2010 at 03:16 PM
Send a ray cast from mouse position then you can get all the information you need from the raycast hit
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hit : RaycastHit;
if (Physics.Raycast (ray, hit, 100)) {
var hitPoint = hit.point;
}
$$anonymous$$e has the vector3 of the point under the mouse though
Answer by hastenshawn · Mar 18, 2012 at 07:35 PM
var clickPoint : Vector3;
function Update()
{
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hit : RaycastHit;
if (Physics.Raycast (ray, hit, 100) && Input.GetButton("Fire1"))
{
Debug.DrawLine (ray.origin, hit.point,Color.red);
clickPoint = hit.point;
}
This will help you visualize the ray and the hit point but you could improve this code. Invert the condition order in the if-statement. The &&-connected conditions in if-statement are processed in order, so only if the first succeeds, the second one is valuated. Raycasting is considered to be too expensive operation (CPU intensive) to be used in every Update call. If you put the raycast condition on the second place of that if-statement, it is not evaluated until Fire1 is held down. And you want to make that Fire1 evaluation with GetButtonDown ins$$anonymous$$d GetButton. That also saves your processing power cos it will only evaluate once per fire click, and not the whole time while it is held pressed.
Your answer
![](https://koobas.hobune.stream/wayback/20220612183011im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Rotate Object to match terrain Slope 1 Answer
making objects clickable when 2 meters away 2 Answers
Stop deletion of the terrain object using Destroy. 1 Answer
Enemy Pooling on a Terrain 1 Answer
Picking Trees with Mouse 5 Answers