- Home /
ScreenToWorldPoint exclude objects or layers?
Hello,
I need to know if you can make an object update it's transform.position every frame according to Camera.ScreenToWorldPoint(), but have it exclude certain objects, or a layer, or if there is any better method.
What I'm trying to do is have an Animation Rig that makes the character's head follow the cursor but the problem I'm facing is that ScreenToWorldPoint includes all objects in the camera's view, so it just ends up on the back of the player's head. Where I want it to be, is in front. On any object in front of the player, but not the player or any objects attached to it.
Is there some way I can get some help understanding this issue and work out a solution? Thanks!
Answer by Namey5 · Mar 13, 2021 at 04:52 AM
ScreenToWorldPoint has nothing to do with actual scene geometry - it just takes a screen-space + depth vector and converts that point to world-space. I'm assuming you are using ScreenPointToRay in combination with a raycast, in which case you can supply a layermask as a parameter to the raycast and ignore your player's layer;
//Set this to your player's layer
[SerializeField] private LayerMask m_LayerMask;
private Camera m_MainCamera;
private void Update ()
{
if (m_MainCamera == null)
m_MainCamera = Camera.main;
//Get the world-space ray from mouse position
Ray mouseRay = m_MainCamera.ScreenPointToRay (Input.mousePosition);
//Perform the raycast using the inverted layermask (ignores the selected layers)
if (Physics.Raycast (mouseRay, out RaycastHit hit, Mathf.Infinity, ~m_LayerMask)
{
//Just set this transform to look at the hit point
transform.rotation = Quaternion.LookRotation (hit.point - transform.position);
}
}
I know this is pretty old but whatever. Sir you saved my night's sleep. Not gonna go into what I needed it for, I just simply and bluntly thank you. Not having experience with the crazy ammount of functions and parameters is so frustrating sometimes, because the solution can be this simple and you just dont see it.