I have made simple Patrol NPC in Unity and everything works fine and NPC has it is own speed (NPC could move to the end point and stop for a while, and goes back to start and stop for a while, this will continuously happen), and I also make the player could move horizontal (a, d in the keyboard) in x axis and vertical (w, s in the keyboard) in z axis and the player has it is own speed. However, when I run the game and starts to move closer to the NPC, the player and NPC will bump into each other, resulting NPC position changes.
Here is the video of it:
Here is the image of components in NPC and Player:
NPC:
Player:
I have tried to change the constraints in the RigidBody of the NPC components by freeze all position and rotation, the problem solved. But when the Player stand in front of the NPC, the NPC just go through the Player, like the collider of the Player is triggered.
Here is the code that I am using:
NPC Script:
public class NPCManager : MonoBehaviour
{
private PlayerManager _playerManager;
private bool moveForward = false;
private float movementSpeed = 1.5f;
private void Awake()
{
_playerManager = GameObject.Find("Player").GetComponent<PlayerManager>();
}
private void Update()
{
if (moveForward)
{
transform.Translate(Vector3.forward * movementSpeed * Time.deltaTime);
}
else
{
StartCoroutine(Hold());
}
}
private void OnGUI()
{
if (_playerManager.isOnChat)
{
GUI.Box(new Rect(Screen.width / 2, Screen.height / 2, 250, 100), "Test.");
}
}
private void OnTriggerEnter(Collider col)
{
if (col.gameObject.name == "First Point")
{
moveForward = true;
}
else if (col.gameObject.name == "Second Point")
{
moveForward = false;
}
}
private IEnumerator Hold()
{
yield return new WaitForSeconds(2.0f);
transform.Translate(-Vector3.forward * movementSpeed * Time.deltaTime);
}
}
Player Script:
[RequireComponent(typeof(CharacterController))]
public class PlayerManager : MonoBehaviour
{
private CharacterController controller;
private Vector3 moveDirection = Vector3.zero;
private float gravity = 20.0f, speed = 5.0f;
public bool isOnChat = false;
private void Awake()
{
controller = GetComponent<CharacterController>();
}
private void Update()
{
if (controller.isGrounded)
{
gameObject.renderer.enabled = true;
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}
private void OnTriggerEnter(Collider col)
{
if (col.gameObject.name == "NPC Follower")
{
isOnChat = true;
}
}
private void OnTriggerExit(Collider col)
{
if (col.gameObject.name == "NPC Follower")
{
isOnChat = false;
}
}
}
How can I solve this?
Any help will be much appreciated!
Thank you so much!