Hey everyone, so I have this bat enemy that once it hits the player, it is supposed to move to a position back in the trees (the red rectangle) and then start chasing the player again. I’m not quite sure how to define the area for it to reposition to or how to pick a random position in that defined area. I tried some code towards the bottom to see if I could get the enemy to hit the player and at least move to a random position on the screen as a start but I couldn’t even get that to work. Any help would be appreciated.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BatController : Enemy
{
Animator animator;
SpriteRenderer spriteRenderer;
public float speed; // speed that bat chases MegaMan
public float repositionSpeed;
public float distBetween;
public float deathDistance;
public float timeToAwake = 3f;
private Transform player; // holds the player
private bool startTimer = false;
private float timer;
void Start()
{
animator = GetComponent<Animator>();
animator.Play("Bat_idle");
timer = timeToAwake;
player = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>(); // get player position
}
void Update()
{
if (Vector2.Distance(transform.position, player.position) <= distBetween)
{
startTimer = true;
if (startTimer)
{
timer -= Time.deltaTime;
if (timer <= 0)
{
animator.Play("Bat_fly");
startTimer = false;
transform.position = Vector2.MoveTowards(transform.position, player.position, speed * Time.deltaTime); // move bat, towards play pos, at certain speed
}
}
}
if (Vector2.Distance(transform.position, player.position) > deathDistance)
{
Destroy(this.gameObject);
}
}
private void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.tag == "Player")
{
float moveY = Random.Range(Camera.main.ScreenToWorldPoint(new Vector2(0, 0)).y, Camera.main.ScreenToWorldPoint(new Vector2(0, Screen.height)).y);
float moveX = Random.Range(Camera.main.ScreenToWorldPoint(new Vector2(0, 0)).x, Camera.main.ScreenToWorldPoint(new Vector2(Screen.width, 0)).x);
Vector2 movePos = new Vector2(moveX, moveY);
transform.position = Vector2.Lerp(transform.position, movePos, repositionSpeed * Time.deltaTime);
}
}
}