I want to set an active target to whatever object the player clicks on. I can conceive of two ways of doing this. The first is to overload OnMouseOver on every selectable object so that, whe nthe button is clicked, whichever object the mouse was over is made active, or, I can use a raycast from camera to the ScreenToWorldPoint, and grab whatever the ray hits as the active target? I’m thinking the later is the best way, but then got to thinking about overhead if the player just keeps clicking over and over again (creating many raycasts). Whic wuld people recommend, or is ther another way?
Why doesn’t this work?:
function Update()
{
if(Input.GetMouseButtonDown(0))
{
var hit : RaycastHit;
if(Physics.Raycast(cam.transform.position,cam.ScreenToWorldPoint(Input.mousePosition),hit,Mathf.Infinity))
{
activeTarget = hit.transform.root.gameObject;
}
}
}
The first time I click on an object, it registers it as the active target correctly. However, it does not switch to any other target that I click on after that.
-
Maybe other objects in your scene don’t have colliders attached?
-
The second parameter should be the rays direction. I believe right now it just points to where the unprojected mouse coordinates are(camera location + near plane distance, more or less)
-
did you try Unity - Scripting API: MonoBehaviour.OnMouseDown()?
I got it working. I switched to using ScreenPointToRay(), and it works fine. Yes, Bearish, I did realize I wasn’t giving it a direction, but even when I added that, I was getting very odd results. ScreenPointToRay() works perfectly.
However, i am still curious as to why you can’t use (semi-pseudo code)
ScreenToWorldPoint(mousePosition) - transform.position
to get the direction for Physics.Raycast.
This should be cam.transform.position, no? (Unless the script is attached to the camera.)
It is cam.transform.position. I was just being lazy, thus my comment that it was semi-pseudo code. That code is what I used as the second parameter in Physics.Raycast(origin, direction,…), but it gave me really weird results, and never correct results.
Maybe you need to normalize it? Shouldn’t matter though.
I’m thinking directions are automatically normalized, but I could be wrong. I thought about that last night, but never did it explicitly b/c I think it is already handled by the engine.