Hi everybody,
I recently added a wolf enemy to my game, and I’m trying to add a behavior that would make the wolf leap forward toward its prey, in this case the player. The problem is that the Y-axis never gets changed, and thus the wolf never leaps forward.
I try to change those axes using two separate AddForce functions, one for the horizontal leap and one for the vertical leap.
The horizontal function works, but sadly the vertical doesn’t work.
What did I do wrong and how could I fix the vertical jump?
Screenshot rigidbody settings: Imgur: The magic of the Internet
Ps. I don’t suspect that Navmash is the problem, but I do use the Navmesh agent to move this enemy.
using UnityEngine;
public class LeapAttackBehaviour : MonoBehaviour
{
[SerializeField] private float jumpHeight = 10f; // Controls the jump height
[SerializeField] private float horizontalMultiplier = 3f; // Controls the jump distance
[SerializeField] private float allowedJumpDistance = 30f;
[SerializeField] private float cooldownTime = 2f;
private float cooldown;
private float maxcooldown = 3f;
private Rigidbody rb;
private EnemyAwareness enemyAwareness;
private void Awake()
{
rb = GetComponent<Rigidbody>();
enemyAwareness = GetComponent<EnemyAwareness>();
cooldown = maxcooldown;
}
private void Update()
{
if (enemyAwareness.GetAggro)
{
float playerDistance = enemyAwareness.Distance;
cooldown -= Time.deltaTime;
if (playerDistance < allowedJumpDistance && cooldown <= 0)
{
JumpTowardsPlayer();
cooldown = maxcooldown;
Debug.Log("Jumping method activated");
}
}
//Debug.Log(enemyAwareness.GetPlayerTransform.position);
}
private void JumpTowardsPlayer()
{
Debug.Log("Jumping behaviour activated");
//Calculate the direction towards the player
Vector3 direction = (enemyAwareness.GetPlayerTransform.position - transform.position).normalized;
//Calculate the jump direction (upward)
Vector3 jumpDirection = Vector3.up * jumpHeight;
//Calculate the leap direction (forward)
Vector3 leapDirection = direction * horizontalMultiplier;
//Apply forces to make the enemy leap
rb.AddForce(jumpDirection, ForceMode.Impulse); //The problem!
rb.AddForce(leapDirection, ForceMode.Impulse);
}
}