Hi everyone. I’m trying to make my enemy face me when in the layer mask, and it’s not working. It won’t flip no matter what I do. It’s probably just something I have overlooked hat’s wrong. Heres the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
public float health;
public float speed;
public int damage;
public Rigidbody2D rb;
public float moveInput;
public float waitTime;
public bool facingRight = true;
//for detecting
public LayerMask detectPlayer;
public Transform detectPlayerPosLeft;
public Transform detectPlayerPosRight;
//left
public float detectPlayerRangeX;
public float detectPlayerRangeY;
//right
public float detectPlayerRangeXRight;
public float detectPlayerRangeYRight;
//attack
public LayerMask whatIsPlayer;
public Transform attackPos;
public Transform attackPos2;
public float attackRange;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
facingRight = true;
moveInput = 0;
}
public void TakeDamage(int damage)
{
health -= damage;
}
private void Update()
{
if(health <= 0)
{
Destroy(gameObject);
}
if (facingRight == true && moveInput > 0)
{
Flip();
}
else if (facingRight == false && moveInput < 0)
{
Flip();
}
//for detecting left
Collider2D[] playerToLeftDetect = Physics2D.OverlapBoxAll(detectPlayerPosLeft.position, new Vector2(detectPlayerRangeX, detectPlayerRangeY), 0, detectPlayer);
for (int i = 0; i < playerToLeftDetect.Length; i++)
{
facingRight = false;
moveInput = -1f;
rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
}
//for detecting right
Collider2D[] playerToRightDetect = Physics2D.OverlapBoxAll(detectPlayerPosRight.position, new Vector2(detectPlayerRangeXRight, detectPlayerRangeYRight), 0, detectPlayer);
for (int i = 0; i < playerToRightDetect.Length; i++)
{
facingRight = true;
moveInput = 1f;
rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
}
//for attacking
Collider2D[] playerToAttack = Physics2D.OverlapCircleAll(attackPos.position, attackRange, whatIsPlayer);
for (int i = 0; i < playerToAttack.Length; i++)
{
playerToAttack[i].GetComponent<PlayerMovement>().TakeDamage(damage);
}
}
void Flip()
{
facingRight = !facingRight;
Vector3 Scaler = transform.localScale;
Scaler.x *= -1;
transform.localScale = Scaler;
}
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(attackPos.position, attackRange);
Gizmos.color = Color.blue;
Gizmos.DrawWireCube(detectPlayerPosLeft.position, new Vector3(detectPlayerRangeX, detectPlayerRangeY, 1));
Gizmos.color = Color.green;
Gizmos.DrawWireCube(detectPlayerPosRight.position, new Vector3(detectPlayerRangeXRight, detectPlayerRangeYRight, 1));
}
}