When the enemy is hit by the player, it will slide backwards until the end of the world. I’m using Terrain as the ground. Is there anything I need to add, or is there an additional LayerMask setting or something?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class EnemyController : MonoBehaviour
{
public float lookRadius = 10f;
Transform target;
NavMeshAgent agent;
CharacterCombat combat;
void Start()
{
target = PlayerManager.instance.player.transform;
agent = GetComponent<NavMeshAgent>();
combat = GetComponent<CharacterCombat>();
}
void Update()
{
float distance = Vector3.Distance(target.position, transform.position);
if (distance <= lookRadius)
{
agent.SetDestination(target.position);
if (distance <= agent.stoppingDistance)
{
CharacterStats targetStats = target.GetComponent<CharacterStats>();
if (targetStats != null)
{
combat.Attack(targetStats);
}
FaceTarget();
}
}
}
void FaceTarget ()
{
Vector3 direction = (target.position - transform.position).normalized;
Quaternion lookRotation = Quaternion.LookRotation(new Vector3(direction.x, 0, direction.z));
transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * 5f);
}
void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawSphere(transform.position, lookRadius);
}
}
Before collide [before collide image] (https://i.sstatic.net/lG4Ukyv9.png)
After collided [after collided image] (https://i.sstatic.net/TMKeLXJj.png)
It will slide until the end of the world [the end of the world] (https://i.sstatic.net/EDSLiIWZ.png)
It’s okay if it still slide, I just need for it not slide too far.
Muhammad Fattan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.