I’d like to detect the coordinates (x, y) on my terrain when the mouse is clicked.
I’ve tried searching Unity answers & Google for answers, but wasn’t able to find something that worked. (Either it was in JS, or for an older version of Unity, or contained project-specific code that I don’t have access to).
The context is I’m making a 2D isometric game and want to be able to right-click to move the character to a specific point.
I don’t have a good conceptual grasp on Raycasts/Raycast semantics, so I’d prefer a specific code snippet if possible, rather than pseudocode.
The following code will move an object to the hit point on a terrain. To use:
Create a terrain
Create an object to place on the terrain
Attach the script to the object to place
Select the object to place in the hierarchy. Drag and drop the terrain onto the ‘goTerrain’ veriable in the inspector
Hit play and right mouse click on the terrain at the position you want to move the object.
using UnityEngine;
using System.Collections;
public class TerrainHit : MonoBehaviour {
public GameObject goTerrain;
void Update() {
if (Input.GetMouseButtonDown (1)) {
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (goTerrain.collider.Raycast (ray, out hit, Mathf.Infinity)) {
transform.position = hit.point;
}
}
}
}
Note this code is a bit different that most of the Raycast() code you will find on UA. Most code uses Physics.Raycast(). This code use Collider.Raycast() so that it cast only against the terrain (which is what you indicated you needed in your question).