Plane.Raycast Example.

Does anyone anyone have an example of Plane.Raycast?

^^ Not much in the way of documentation for it :slight_smile:

Thanks.

I realize this answer is quite late. I was looking for the same thing as the original poster and had to do some studying… If there are other people searching for this answer sometime, here is a small example I hope will help :slight_smile:

var plane : Plane = new Plane(Vector3.up, Vector3.zero);;

function LateUpdate()
{
	if (Input.GetMouseButton(0))
	{
		var ray = Camera.main.ScreenPointToRay(Input.mousePosition);

		var ent : float = 100.0;
		if (plane.Raycast(ray, ent))
		{
			Debug.Log("Plane Raycast hit at distance: " + ent);
			var hitPoint = ray.GetPoint(ent);
			
			var go = GameObject.CreatePrimitive(PrimitiveType.Cube);
			go.transform.position = hitPoint;
			Debug.DrawRay (ray.origin, ray.direction * ent, Color.green);
		}
		else
			Debug.DrawRay (ray.origin, ray.direction * 10, Color.red);

	}
}
1 Like

better late than never!

Definitely- I found this really useful, thanks so much. Use: isometric strategy game, building placement.

Works great, thanks…

One thing, there’s no need to define ent, just declare it. Raycast() will set it for you and that 100.0 is just getting overwritten…

Cheers

Thanks a Million. Finally figured this out with my camera being rotated. here is my solution

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
public class MouseCursor : MonoBehaviour
{
    Plane plane;
    public LoadGrid loadGrid;
    Vector3Int ClickedTile;
    public Tiledata tiledata;
    private void Start()
    {
        plane = new Plane(loadGrid.transform.up, Vector3.zero);//camera is on an angle so the plane must use the same up as the ground in my case a tileMapgrid
    }
    void Update()
    {
        if (Input.GetMouseButtonUp(0))
        {
            var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            float ent;
            if (plane.Raycast(ray, out ent)) //gets the hitpoint on the plane
            {
             
                var hitPoint = ray.GetPoint(ent);
                hitPoint.z = hitPoint.z - 0.5f;  //was off by .5
             
             
                ClickedTile = loadGrid.TopTileMap.WorldToCell(new Vector3(hitPoint.x,0,hitPoint.z)); //the clicked tile
                Vector3 temp = loadGrid.TopTileMap.CellToWorld(ClickedTile); //convert back to move cursor to position
                this.transform.position = new Vector3(temp.x, 0, temp.z + 0.5f); //move the cursor... was also off by 0.5f
                tiledata = loadGrid.GetTilePoint(new Vector2Int(ClickedTile.x, ClickedTile.y), loadGrid.DefaultNoiseSettings); //returns data about the selected tile
            }
         
        }
    }
}