Im trying to make a jump enemy within this AI : using UnityEngine; using…
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Im trying to make a jump enemy within this AI : using UnityEngine; using System.Collections; using System.Collections.Generic;
namespace BreadcrumbAi{ //[System.Serializable] public class Ai : MonoBehaviour { #region Editor Variables // EDITOR VARIABLES // public bool _CanFollowPlayer, _CanFollowBreadcrumbs, _CanFollowAi, _CanWander, _CanPatrol, _CanIgnoreAi, // coming soon _CanWanderAnywhere, _CanHover, _CanFlee, _CanJump, _CanLongJump, _IsJumping, _HasAvoidance, _HasEdgeAvoidance, _HasVision, _HasFrontVision, _IsMelee, _IsRanged, _IsGround, _IsAir, _IsInvincible, _IsResurrected;
public float followSpeed, wanderSpeed, patrolSpeed, rotationSpeed, avoidSpeed,
jumpDistance, jumpForce, longJumpForce,
followDistance, wanderDistance, attackDistance, visionDistance, avoidDistance, edgeDistance, otherAiDistance,
wanderTimeLimit, wanderTimeRate,
hoverHeight, hoverForce,
Health;
//[SerializeField]
public PlayerVitals playerVitals;
public Transform player;
public Transform raycastPoint;
public Transform raycastTarget; //found or make one on player and drag to this script in the inspector
#endregion
// States are used for adding actions, animations, sounds, etc to your Ai.
#region STATES
public enum LIFE_STATE{
IsAlive,
IsDazed, // coming soon
IsDead,
IsInvincible,
IsResurrected};
public LIFE_STATE lifeState = LIFE_STATE.IsAlive;
public enum VISION_STATE{
CanSeeNothing,
CanSeePlayer,
CanSeeBreadcrumb,
CanSeeFollowAi,
CanSeeFollowAiTierTwo,
CanSeeWaypoint};
public VISION_STATE visionState = VISION_STATE.CanSeeNothing;
public enum MOVEMENT_STATE{
IsIdle,
IsFollowingPlayer,
IsFollowingBreadcrumb,
IsFollowingAi,
IsFollowingAiTierTwo,
IsWandering,
IsPatrolling};
public MOVEMENT_STATE moveState = MOVEMENT_STATE.IsIdle;
public enum ATTACK_STATE{
CanNotAttack,
CanAttackPlayer,
CanAttackOther}; // coming soon
public ATTACK_STATE attackState = ATTACK_STATE.CanNotAttack;
#endregion
// GAMEOBJECTS
[HideInInspector]
public Transform Player, // Targeted Player (works with multiple players)
FollowingPlayer, // Last Targeted Player
Breadcrumb, // Closest Located Breadcrumb
FollowingAi, // Ai To Follow
Waypoint, // Current Waypoint Targeted
Hover, // Hover Start Pos
Edge, // Edge Avoidance Start Pos
LongJumpDetector, // Jump to start Pos
JumpDetector; // Jump detector
// LAYERS
[HideInInspector]
public LayerMask playerLayer, // Layer : Player
enemyLayer, // Layer : Enemy
breadcrumbLayer, // Layer : Breadcrumb
waypointLayer, // Layer : Waypoint
obstacleLayer; // Layer : Obstacle
// TAG STRINGS
[HideInInspector]
public string Head;
// PRIVATE VARIABLES
public bool _IsWandering;
private bool _IsAvoiding; // Used for avoidance, removes velocity after avoidance
private bool _HasWanderPos;
private Vector3 currentWanderPos;
private Vector3 wanderPos; // Sets next random wander position
private float wanderTimer, wanderNext; // Used for timing the wander time limit
private RaycastHit hit;
private Rigidbody rb;
private Collider zombieCollider;
void Start(){
player = GameObject.Find("Player").transform;
raycastTarget = GameObject.Find("RaycastTarget").transform;
playerVitals = FindObjectOfType(typeof(PlayerVitals)) as PlayerVitals;
rb = GetComponent<Rigidbody>();
zombieCollider = GetComponentInChildren<Collider>();
StartCoroutine(this.Ai_Lists());
StartCoroutine(this.Ai_Layers());
Health = Random.Range(10, 20);
}
void Update(){
Ai_LifeState();
Ai_Controller(); // Controls Ai Movement & Attack States
//Ai_Avoidance(~(breadcrumbLayer | enemyLayer | playerLayer | waypointLayer)); // Controls Ai wall avoidance
Ai_Hover();
if (IsGrounded()){
_IsJumping = false;
}
}
void FixedUpdate (){
//Ai_Controller(); // Controls Ai Movement & Attack States
Ai_Avoidance(~(breadcrumbLayer | enemyLayer | playerLayer | waypointLayer)); // Controls Ai wall avoidance
}
private void Ai_Controller(){
// Checks if following player is enabled and a player has been found
if (_CanFollowPlayer && this.Ai_FindPlayer())
{
_HasWanderPos = false; // TODO: this needs to be fixed
visionState = VISION_STATE.CanSeePlayer;
// CHANGE THIS TO FLEE (_CanFlee)
if(_IsRanged){ // Is this a ranged ground unit?
if(Vector3.Distance(transform.position,Player.position) > followDistance){
moveState = MOVEMENT_STATE.IsFollowingPlayer;
attackState = ATTACK_STATE.CanNotAttack;
Ai_Movement(Player.position, followSpeed);
} else if(_CanFlee && Vector3.Distance(transform.position,Player.position) <= attackDistance) {
moveState = MOVEMENT_STATE.IsFollowingPlayer;
attackState = ATTACK_STATE.CanNotAttack;
Ai_Flee();
} else {
moveState = MOVEMENT_STATE.IsIdle;
attackState = ATTACK_STATE.CanAttackPlayer;
Ai_Rotation(Player.position);
}
} else if(_IsMelee){ // Is this a melee ground unit?
if(Vector3.Distance(transform.position,Player.position) > followDistance){
//GetComponent<Rigidbody>().isKinematic = false;
moveState = MOVEMENT_STATE.IsFollowingPlayer;
attackState = ATTACK_STATE.CanNotAttack;
Ai_Movement(Player.position, followSpeed);
if (Vector3.Distance(transform.position, Player.position) > (followDistance + 1f))
{
//Debug.Log("KINEMATIC FALSE");
//GetComponent<Rigidbody>().isKinematic = false;
rb.isKinematic = false;
//GetComponent<Rigidbody>().detectCollisions = true;
}
else {
//Debug.Log("KINEMATIC TRUE");
//GetComponent<Rigidbody>().isKinematic = true;
rb.isKinematic = true;
//GetComponent<Rigidbody>().detectCollisions = false;
}
} else if(Vector3.Distance(transform.position,Player.position) <= attackDistance) {
//GetComponent<Rigidbody>().isKinematic = true;
moveState = MOVEMENT_STATE.IsIdle;
attackState = ATTACK_STATE.CanAttackPlayer;
Ai_Rotation(Player.position);
/*if (Vector3.Distance(transform.position, Player.position) <= (attackDistance + 1f))
{
Debug.Log("KINEMATIC TRUE");
GetComponent<Rigidbody>().isKinematic = false;
GetComponent<Rigidbody>().detectCollisions = true;
}*/
}
}
Debug.DrawLine(raycastPoint.position, raycastTarget.position, Color.red);
// Checks if following breadcrumbs is enabled as well as if a player was spotted and a breadcrumb has been found
} else if(_CanFollowBreadcrumbs && FollowingPlayer && this.Ai_FindBreadcrumb()){
_HasWanderPos = false; // TODO: this needs to be fixed
visionState = VISION_STATE.CanSeeBreadcrumb;
moveState = MOVEMENT_STATE.IsFollowingBreadcrumb;
attackState = ATTACK_STATE.CanNotAttack;
Ai_Movement(Breadcrumb.position, followSpeed);
//Debug.DrawLine(raycastPoint.position, Breadcrumb.position, Color.green);
// Checks if following other ai is enabled and if an ai has been found
} else if(_CanFollowAi && this.Ai_FindAi()){
_HasWanderPos = false; // TODO: this needs to be fixed
visionState = VISION_STATE.CanSeeFollowAi;
moveState = MOVEMENT_STATE.IsFollowingAi;
attackState = ATTACK_STATE.CanNotAttack;
if(Vector3.Distance(transform.position, FollowingAi.position) > otherAiDistance){
Ai_Movement(FollowingAi.position,followSpeed);
} else {
moveState = MOVEMENT_STATE.IsIdle;
}
//Debug.DrawLine(raycastPoint.position, FollowingAi.position, Color.magenta);
// Checks if following other ai is enabled and if a tier two ai has been found
} else if(_CanFollowAi && this.Ai_FindAiTierTwo()){
_HasWanderPos = false; // TODO: this needs to be fixed
visionState = VISION_STATE.CanSeeFollowAiTierTwo;
moveState = MOVEMENT_STATE.IsFollowingAiTierTwo;
attackState = ATTACK_STATE.CanNotAttack;
if(Vector3.Distance(transform.position, FollowingAi.position) > otherAiDistance){
Ai_Movement(FollowingAi.position,followSpeed);
} else {
moveState = MOVEMENT_STATE.IsIdle;
}
//Debug.DrawLine(raycastPoint.position, FollowingAi.position, Color.yellow);
// Checks if wandering is enabled and if the timer has reached its limit
} else if( _CanWander && wanderTimer < wanderTimeLimit) {
visionState = VISION_STATE.CanSeeNothing;
attackState = ATTACK_STATE.CanNotAttack;
Ai_Wander ();
// Checks if patrolling is enabled and a waypoing has been found
} else if(_CanPatrol && this.Ai_FindWaypoint()) {
_HasWanderPos = false; // TODO: this needs to be fixed
visionState = VISION_STATE.CanSeeWaypoint;
moveState = MOVEMENT_STATE.IsPatrolling;
attackState = ATTACK_STATE.CanNotAttack;
Ai_Movement(Waypoint.position, patrolSpeed);
//Debug.DrawLine(raycastPoint.position, Waypoint.position, Color.white);
// Nothing is found, reset all variables
} else {
Ai_Reset();
}
}
private void Ai_Reset(){
Player = null;
FollowingPlayer = null;
Breadcrumb = null;
FollowingAi = null;
Waypoint = null;
wanderTimer = 0;
moveState = MOVEMENT_STATE.IsIdle;
attackState = ATTACK_STATE.CanNotAttack;
}
// Move the rigidbody forward based on the speed value
private void Ai_Movement(Vector3 position, float speed){
if(_CanJump && CanJump()){
if(moveState == MOVEMENT_STATE.IsFollowingPlayer ||
moveState == MOVEMENT_STATE.IsFollowingAi ||
moveState == MOVEMENT_STATE.IsFollowingAiTierTwo){
Ai_Jump();
}
}
if(Ai_EdgeAvoidance() && !_IsJumping){
rb.MovePosition(rb.position + transform.forward * Time.deltaTime * speed);
} else if(_CanLongJump){
if(moveState == MOVEMENT_STATE.IsFollowingPlayer ||
moveState == MOVEMENT_STATE.IsFollowingAi ||
moveState == MOVEMENT_STATE.IsFollowingAiTierTwo){
Ai_LongJump();
}
}
Ai_Rotation(position);
}
// Rotate the Ai to look towards it's target at a set Rotation speed
private void Ai_Rotation(Vector3 position){
Vector3 playerPos = Vector3.zero;
if(_IsGround){
playerPos = new Vector3(position.x,transform.position.y,position.z); // Adjust Y position so Ai doesn't rotate up/down
} else if(_IsAir){
playerPos = new Vector3(position.x,position.y,position.z);
}
rb.MoveRotation(Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(playerPos - transform.position), rotationSpeed));
}
private void Ai_Flee(){
rb.MoveRotation(Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(transform.position - Player.position), rotationSpeed));
if(Ai_EdgeAvoidance()){
rb.MovePosition(rb.position + transform.forward * Time.deltaTime * followSpeed);
}
}
public void Ai_Jump(){
if(IsGrounded() && !_IsJumping){
rb.AddForce((Vector3.up * jumpForce) + (transform.forward * (jumpForce/2)), ForceMode.VelocityChange);
_IsJumping = true;
}
}
public void Ai_LongJump(){
if(IsGrounded() && !_IsJumping){
if(Physics.Linecast(LongJumpDetector.position, LongJumpDetector.position + (-Vector3.up * edgeDistance))){
rb.AddForce((Vector3.up + transform.forward) * longJumpForce, ForceMode.VelocityChange );
_IsJumping = true;
}
//Debug.DrawLine(LongJumpDetector.position,LongJumpDetector.position + (-Vector3.up * edgeDistance));
}
}
// This wander function selects a random location around the Ai and moves towards it.
// This will be update in the future to allow specific wander radius rather than "anywhere"
private void Ai_Wander(){
wanderTimer += Time.deltaTime;
if(wanderTimer >= wanderTimeLimit){
_IsWandering = false;
} else {
_IsWandering = true;
To implement a jumping enemy AI within the given script, you need to ensure that the jump functionality is correctly integrated into the AI's behavior. It looks like the script already includes variables and methods related to jumping, such as _CanJump, Ai_Jump(), and checks for whether the AI is currently jumping (_IsJumping). To successfully make the enemy jump as part of its behavior, follow these steps:
Ensure Jump Conditions Are Met: The AI should only attempt to jump when it's appropriate for its current behavior and environment. For example, you might want the AI to jump when following the player or fleeing, and only if there's an obstacle in its path or a gap it needs to cross.
Check for Ground: Before jumping, always ensure the AI is grounded. You've got a method IsGrounded() which likely checks this, so make sure it's being used to prevent the AI from attempting to jump while already in the air.
Invoke Jump at the Right Time: Determine the specific conditions under which you want the AI to jump. For example, if the AI is following the player and encounters an obstacle, or if it's part of their attack pattern. You've already got an Ai_Movement method where jumping is considered, but ensure the logic for deciding when to jump is sound and fits the behavior you desire.
Adjust Jump Parameters: Experiment with the jumpForce and longJumpForce parameters to get the jump behavior you want. These will control how high and how far the AI jumps. You might need different values depending on the situation (e.g., a small hop to clear a low obstacle vs. a long jump across a gap).
Integrate Jumping with Other Behaviors: If the AI has multiple behaviors (e.g., following, fleeing, patrolling), ensure that jumping can smoothly integrate with these. For instance, if the AI decides to jump while following the player, it should continue following after landing.
Feedback and Iteration: Test the jumping behavior in various scenarios to see how it performs. You might find that you need to adjust when the AI decides to jump, or fine-tune the jump forces. Be prepared to iterate on your implementation.
Here's a sample adjustment to the Ai_Movement method focusing on integrating the jump logic more clearly:
private void Ai_Movement(Vector3 position, float speed){
if(_CanJump && IsGrounded() && !_IsJumping){
// Determine if we need to jump based on some condition, e.g., obstacle ahead
if(ShouldJump()) { // You'll need to implement ShouldJump to check for obstacles or reasons to jump
Ai_Jump();
}
}
if(Ai_EdgeAvoidance() && !_IsJumping){
rb.MovePosition(rb.position + transform.forward * Time.deltaTime * speed);
} else if(_CanLongJump && ShouldLongJump()) { // Implement ShouldLongJump similar to ShouldJump
Ai_LongJump();
}
Ai_Rotation(position);
}
This requires implementing ShouldJump and ShouldLongJump methods that check for conditions under which a jump or long jump is appropriate. These could involve checking for obstacles, gaps, or if the AI is in an attack mode where jumping is part of the attack pattern.