So I have this NPC Passive_Enemy (by stander), when the player gets close to him it should turn to look at him then runaway the opposite direction of the player, and when he hit’s an object like wall or anything else it should turn to any direction away from the player and move that way. Here is what I have so far. Also for some reason when I get close to the Passive_Enemy he starts moving even though I have not set any movement yet…weird. I added a picture of the inspector for Passive_Enemy as a file.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Passive_Enemy : MonoBehaviour
{
private float _speed = 3.0f;
private Transform _player;
private float _distance;
private bool _alive;
private bool _playerInRange;
private Rigidbody _rb;
// Use this for initialization
void Start () {
_player = GameObject.Find("Player").transform;
_rb = GetComponent<Rigidbody>();
_alive = true;
}
// Update is called once per frame
void Update () {
CheckDistance();
if(_playerInRange)
RunAway();
}
private void CheckDistance()
{
_distance = Vector3.Distance(this.transform.position, _player.transform.position);
if (_distance > 2 && _distance <= 10)
{
_playerInRange = true;
_rb.constraints = RigidbodyConstraints.None;
}
else
{
_playerInRange = false;
_rb.constraints = RigidbodyConstraints.FreezeRotation;
}
}
private void RunAway()
{
//Turning enemy to look at player
transform.LookAt(_player);
this.transform.rotation = Quaternion.Inverse(this.transform.rotation);
}
}