I want my enemy to collide with my player, but the enemy thinks it is in the same position as the player when it is not. I have attached a screenshot of the game and the enemy’s movement script. Any help with this issue would be great. Sorry if this isn’t adequate information. This is my first post to this forum.
//Declarations
public float SpeedCorrector = 1f;
float WonderRope = 0;
public Rigidbody2D Player;
Vector2 Narnia; //actual place going
float[] Jemerny = new float[4]; //actual box thing-a-ma-jig
public float moveSpeed = 10f;
float zoomies = 5f;
public Rigidbody2D rb;
public int BoxBig = 100;//cage size indicator
Vector2 movement;
bool Clippy = false;//is supposed to check if the gonglos are on a quest or not
float stopTime = 0f; // Timer for stopping movement
public float stopDuration = 5f; // Duration to stop after collision
public float minDistance = 20f; // Minimum distance for random destination
Vector2 confusion;
void Start()
{
// this is the cage for gonglos, i think it goes here????
Jemerny[0] = rb.position.y + BoxBig; //Top
Jemerny[1] = rb.position.x + BoxBig;//right
Jemerny[2] = rb.position.y - BoxBig;//bottom
Jemerny[3] = rb.position.x - BoxBig;//left
zoomies = moveSpeed/2;
}
void FixedUpdate()
{
WonderRope = Math.Abs(Player.position.x - rb.position.x) + Math.Abs(Player.position.y - rb.position.y);
if (stopTime > 0)
{
stopTime -= Time.fixedDeltaTime; // Decrease the stop timer
if (WonderRope >= 500)
{
return; // Exit early if we're in stop mode
}
}
//this determines his objective before he tries going anywhere
if (!Clippy)
{
Narnia = SetRandomDestination();
movement = (Narnia - rb.position);
Clippy = true;
}
if (WonderRope < 500)
{
Narnia = Player.position;
movement = (Narnia - rb.position);
Clippy = false;
rb.MovePosition(rb.position + movement * moveSpeed * Time.fixedDeltaTime);
}
else
{
rb.MovePosition(rb.position + movement * zoomies * Time.fixedDeltaTime);
}
// Check if the enemy is close to the target position
if (Vector2.Distance(rb.position, Narnia) < 0.1f) // Use a small threshold
{
Clippy = false; // Reset the flag to move again
stopTime = stopDuration/2;
}
Debug.Log($"Enemy position: {rb.position}, Enemy Target Position: {Narnia}, Enemy Movement: {movement}, Distance to Player: {WonderRope}");
}
void OnCollisionEnter2D(Collision2D collision)
{
Debug.Log($"colliding with: {collision.gameObject.tag}");
if (collision.gameObject.tag == "player")
{
stopTime = stopDuration; // Start the stop timer
}
}
public Vector2 SetRandomDestination()
{
do
{
confusion.x = UnityEngine.Random.Range(Jemerny[3], Jemerny[1]);
confusion.y = UnityEngine.Random.Range(Jemerny[2], Jemerny[0]);
} while (Vector2.Distance(rb.position, confusion) < minDistance); // Ensure it's far enough
return confusion;// Set the new destination
```