- Home /
Unity 3d: aggresive monster
I am trying to program a monster prefab to follow a player if it sees the player, but its all glitchy. It just follows the player, even when it doesn't see it. What is wrong with my code?
using System.Collections.Generic; using UnityEngine;
public class Monster : MonoBehaviour {
public Transform Player;
int MoveSpeed = 1;
int MaxDist = 5;
int MinDist = 0;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
transform.LookAt(Player);
if(Vector3.Distance(transform.position,Player.position) >= MinDist)
{
transform.position += transform.forward * MoveSpeed * Time.deltaTime;
if(Vector3.Distance(transform.position,Player.position) <= MaxDist)
{
//Here Call any function U want Like Shoot at here or something
}
}
}
},I'm trying to create a monster for the game. I want it to chase the player when it sees the play and stop when it doesn't. So far, its glitchy. It chases the people, even when it doesn't see the player. Does anyone know what is wrong with my code?
using System.Collections.Generic; using UnityEngine; public class Monster : MonoBehaviour {
public Transform Player;
int MoveSpeed = 1;
int MaxDist = 5;
int MinDist = 0;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
transform.LookAt(Player);
if(Vector3.Distance(transform.position,Player.position) >= MinDist)
{
transform.position += transform.forward * MoveSpeed * Time.deltaTime;
if(Vector3.Distance(transform.position,Player.position) <= MaxDist)
{
//Here Call any function U want Like Shoot at here or something
}
}
}
}
Answer by Tanoshimi2000 · Apr 26, 2018 at 11:27 AM
You need to use a RayCast from the eyes of the monster in the direction of the character. If the raycast hits the character, and he's close enough, then the monster can "see" him.
To clarify, RayCast (or one of the other casts) shoots a line from one point to another, and then tells you the first item that gets hit by that line. Think of it as a laser pointer. So, if that hits a wall, then there's a wall between your monster and the character. If it hits the character, then the monster can see the character.