- Home /
C# Raycast Code not working
Hi,
I've made a raycast script to activate an enemy's movement script when it sees the player. When I position the player in front of the enemy, the enemy doesn't start moving. This is the script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class sheepVision : MonoBehaviour
{
public meshNavigator navScript;
public Transform target;
RaycastHit hit = new RaycastHit();
Ray ray = new Ray();
void Start ()
{
navScript = GetComponent <meshNavigator> ();
navScript.enabled = false;
}
void Update ()
{
ray.origin = transform.position;
ray.direction = target.position;
if (Physics.Raycast(ray, out hit, Mathf.Infinity) && hit.transform.tag == "Player")
{
navScript.enabled = true;
}
}
}
Thanks for any help, Alex
You're confused about direction and position. You can't do it this way:
ray.direction = target.position;
Direction isn't position. You mentioned wanting it to trigger once the player is in front of them, so just do it that way. Note that this will depend on how your object is set up, but we'll assume that your object's forward vector is really forward.
ray.direction = transform.forward;
Answer by mjdb3d · Sep 17, 2018 at 05:47 PM
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class sheepVision : MonoBehaviour
{
public meshNavigator navScript;
public Transform target;
RaycastHit hit = new RaycastHit();
Ray ray = new Ray();
void Start ()
{
navScript = GetComponent <meshNavigator> ();
navScript.enabled = false;
}
void Update ()
{
ray.origin = transform.position;
ray.direction = target.position - transform.position;
if (Physics.Raycast(ray, out hit, Mathf.Infinity) )
{
if(hit.transform.tag == "Player")
{
navScript.enabled = true;
}
}
}
}
Answer by _Venus_ · Sep 17, 2018 at 05:03 PM
If you want to move the enemy and have it only move when it "sees" the player, try looking into frustum plates. I don't know if raycast would be the best for this situation, but i think the problem is your Ray. You have to define the direction for the ray.
Your answer
Follow this Question
Related Questions
Raycast from 2D canvas object to world space 1 Answer
Obstacle Avoidance in Unity, using raycasts. C# 1 Answer
Raycast goes throught objects [C#] 1 Answer
Raycast function doesn't work. 1 Answer
Distribute terrain in zones 3 Answers