Hello,
I am trying to make volleyball type game in 2D with capsules as players, I am struggling with the AI part. The player doesn’t jump when the ball is close to ball distance, but it jumps when collision.
I want to be able to create an AI that moves smoothly and jumps when near the ball. Any help?
Many Thanks
private float moveSpeed = 5;
private float jumpForce = 5;
private float playerDistance;
private Rigidbody2D rb2d;
private Transform myTransform;
private Transform target;
private bool grounded = false;
void Start()
{
myTransform = this.GetComponent<Transform>();
rb2d = GetComponent<Rigidbody2D>();
target = GameObject.FindWithTag("Ball").transform;
}
void FixedUpdate()
{
playerDistance = Vector3.Distance(transform.position, target.position);
if (playerDistance < 6f)
{
EnemyChase();
}
if (playerDistance < 1f)
{
EnemyJump();
}
}
private void EnemyChase()
{
myTransform.position += (target.position - myTransform.position).normalized * moveSpeed * Time.deltaTime;
}
private void EnemyJump()
{
transform.Translate(Vector3.up * jumpForce * Time.deltaTime);
}
void OnCollisionEnter2D(Collision2D other)
{
if(other.gameObject.tag == "Ball")
{
EnemyJump();
}
}