Picking and Raycasting

Hi everyone, total noob here.

I was wondering how to make this work. I’m using Unity’s water plane and I have a boat that I want to move depending on where the user clicks. I’m using ScreenPointToRay to cast a ray to see where it hits on the body of water, and thus, where my boat should go.

Thing is, I have no clue in how to determine where that is.

  1. Does the ray collide with the water, or do I need to hide a plane just under the sea level?

2)How do I use “hitinfo” that is described on this page? Unity - Scripting API: Physics.Raycast
I assume this will be the key in determining where the ray hit. Am I wrong?

function Update () {
    if (Input.GetButtonDown ("Fire1")) {
        // Construct a ray from the current mouse coordinates
        var ray : Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
        if (Physics.Raycast (ray)) {
            // HOW !!! Thanks.
        }
    }
}

Thanks for helping me !

Well, you can take the position and turn it into Vector3 coodinates fairly easily. This is a snippit from my current project grabbing screen and world coords from a raycast.

if (Physics.Raycast (ray, hit)){			
	mousePosX = hit.point.x; //world X coord that the hit took place at
	mousePosZ = hit.point.z; //world Z coord that the hit took place at
				
	xMPos = Input.mousePosition.x; //Screen X position of mouse
	yMPos = Input.mousePosition.y; //Screen Y position of mouse

Ok so adding hit to the parenthesis and using hit.point.x (and z) should tell me that collision point? Thanks.

The word “hit” is not strictly necessary. If you specify the variable, and it can be any name you want, it stores the information of the Raycast’s intersection with the other object. From that variable you can pull lots of information, including location. Hope that helps. :slight_smile:

Since the water plane doesn’t actually collide, you can’t raycast to it. Create a Plane.Raycast to solve this…

var water : Transform;

function Update(){
	if(Input.GetButtonDown("fire1")){
		var mouseRay : Ray= Camera.main.ScreenPointToRay(Input.mousePosition);
		var plane : Plane = new Plane(Vector3.up, water.position);
		var distance : float =0.0;
		plane.Raycast(mouseRay, distance);
		if(distance > 0.0){
			var hitPoint : Vector3 = mouseRay.GetPoint(distance);
			// do something with hitPoint....
		}
	}
}

Cool Thanks, BigMisterB. I already created a plane last night to make sure it would collide. Im going to use this plane to determine a hit. It should work with a plane placed in the editor as well, shouldn’t it?

The plane needs to have a collider in order to register on a raycast. But if you create a plane with a collider in the editor, your objects will collide with it. That’s probably not the behaviour you’re looking for just to enable a raycast.

Will keep that in mind, thanks. Getting back to it tonight, after work !