- Home /
Issues with Linecast/Raycast
Hi, I'm making a 3rd person rpg and am attempting to implement some collision detection for the camera. I've set it up so that the camera has a child empty 1 unit to it's right. I've written a script for this empty that will linecast from the transform.position of the camera to the transform.position of the empty. If there's a hit, it's logged. Up to this point, everything works as expected.
From this point, I mirror the process and set up an empty with the same script for the left side of the camera. Now, this linecast works, but for some reason, the other one no longer works. If I disable one, the other works, and vice versa, but neither will work at the same time.
Here's the script that I've attached to the empties:
public class CamSensor : MonoBehaviour
{
private Transform cameraTransform;
void Start()
{
cameraTransform = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<Transform>();
}
void Update()
{
RaycastHit hit;
if (Physics.Linecast(cameraTransform.position, transform.position, out hit)) //if there's an object between the camera and the sensor
{
Debug.Log("hit from " + gameObject.name + " sensor.");
}
else
{
Debug.Log("no hit");
}
}
}
Any ideas as to why this is happening? I've also tried using Raycasts but ran into the same issue. If anyone wants to see the raycast code, just let me know and i'll put it up. As always, many thanks in advance!
$$anonymous$$inor update, I thought that having both Linecasts originate from the same point might be causing the issue so I changed that up but it did not solve the issue.
Update 2... For the heck of it, I tried a raycast on one side and a linecast on the other, but this didn't work either.
Answer by EvilTak · Feb 06, 2015 at 03:05 AM
Instead of putting such a script on both empty objects, remove the empty objects and add this script on the main camera:
public float distance;
void FixedUpdate() {
Vector3 left = transform.position + transform.left * distance;
Vector3 right = transform.position + transform.right * distance;
RaycastHit hit;
if(Physics.Raycast(transform.position, left, out hit)) {
//left hit
}
if(Physics.Raycast(transform.position, right, out hit)) {
//right hit
}
Where distance is how far you want to raycast to the left and right in meters.
Ha, I was trying something like that earlier but was adding transform.left ins$$anonymous$$d of multiplying and getting the wrong behavior. I guess I need to brush up on my vector math. Thanks for the pointer :) Also, I discovered that both Linecasts were indeed working but that the debug.logs were not giving me the correct information. Thanks for taking the time to help!
Your answer
Follow this Question
Related Questions
issues with jumping and linecast2d and raycast2d 0 Answers
Need help with Third person shooter 0 Answers
Pointcast? - Raycast Point X from same Point X 0 Answers
Multiple linecasts question 1 Answer
Ray/line casting for camera angle 1 Answer