- Home /
Raycast through object
Hey guys, my player at the moment rotates to the position of the mouse, but when the mouse gets behind a mountain, the player stops rotating to the mouse and when I get out of the mountain it again starts following. Does someone know how the player can also rotate to the mouse position when the mouse is behind the mountain? (It's a 3D game)
Here's the playerrotatetomouse script:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class RayCamera : MonoBehaviour { public Camera aremac;
void Start() { //Cursor.lockState = CursorLockMode.Locked; }
void FixedUpdate(){ RaycastHit hit; Ray ray = aremac.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast (ray, out hit)) {
transform.LookAt(new Vector3(hit.point.x, transform.position.y, hit.point.z)); // Do something with the object that was hit by the raycast.
}
} }
Answer by asafsitner · Mar 16 at 12:53 PM
Take a look at LayerMask; it allows you to set objects in a layer that the raycast would then ignore, and effectively "go through" them.
I'd suggest setting the mask as a property or field that's exposed to the Inspector for easier editing. Then your code would look something like:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RayCamera : MonoBehaviour
{
public Camera aremac;
public LayerMask hitMask; // define this in the inspector! remember that checkmarks mean layers to hit
public float rayRange = float.MaxValue; // making this a public field is optional, but the value is needed for the Raycast call
void Start()
{
//Cursor.lockState = CursorLockMode.Locked;
}
void FixedUpdate()
{
RaycastHit hit;
Ray ray = aremac.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, rayRange, hitMask))
{
transform.LookAt(new Vector3(hit.point.x, transform.position.y, hit.point.z)); // Do something with the object that was hit by the raycast.
}
}
}
Thank you very much for the reply! So I just have to attach this to my player and select the layer, the ray should ignore?
Should work, yes, but don't forget to choose which layers to hit or ignore in the Inspector. LayerMask is very handy!
If you want to keep it super simple, you can also just set the object you want to ignore int other Ignore Raycast layer (more details in the Physics.DefaultRaycastLayers documentation).
Your answer
Follow this Question
Related Questions
Is there a way to get mouse position in 3D space at a given y-value? 2 Answers
2D - finding object at mouse position 2 Answers
Weird navigation issue 0 Answers
What is error on Raycasting? 0 Answers
Raycast2d not working C# :( 1 Answer