- Home /
raycast isn't working in my movetowards script.
the script i'm using to have an enemy see a player and move to the position that it saw him at isn't working 100%. It only sees in a straight line from the start point of the enemy. so if I round a corner the enemy moves to the edge of the corner and waits but doesn't cast another ray to see me standing right in front of it.
using UnityEngine;
using System.Collections;
public class Spark : MonoBehaviour {
public GameObject Player;
private Vector3 PlayerPos;
private bool PlayerSeen;
public float Speed;
private RaycastHit hit;
void Start () {
//Player = GameObject.Find("FPSController");
}
void Update () {
transform.LookAt (Player.transform.position);
Vector3 RayStart = transform.forward;
Vector3 RayEnd = Player.transform.position;
if (Physics.Raycast (RayStart, RayEnd, out hit, 20)) {
if (hit.collider.gameObject.tag == "Player") {
PlayerPos = Player.transform.position;
//Debug.Log(PlayerPos);
}
}
float step = Speed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, new Vector3(PlayerPos.x, 1, PlayerPos.z), step);
}
}
Answer by OmniKeith · Apr 13, 2015 at 09:32 PM
Again, I ended up fixing this one myself with a quick work around. It's still not what I want it to be but I know why it isn't working. The RayCast goes from point a to point b and then out to the ray... so since the enemy object is always facing the player i just created a new vector3 with the forward added to the enemies coordinates and draw a ray from point a to the new vector and out 20f. I would like to fix the problem of having to always have my enemy rotate to the players direction because I may want to use a better more featured model and I want the player to be able to see its back.