Created
June 22, 2021 05:33
-
-
Save RageshAntony/622950b1113ab63d53dd668a4f8f0e60 to your computer and use it in GitHub Desktop.
To detect the Player if he approches the enemy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
public class Enemy : MonoBehaviour | |
{ | |
private Rigidbody2D rigidBodyComp; | |
int i = 0; | |
float initialPos,currentPos; | |
private Vector2 dir = Vector2.left; | |
private Animator anim; | |
[SerializeField] private int speed; | |
[SerializeField] private float leftEnd, RightEnd; | |
[SerializeField] private Vector2 sizeLeft,sizeRight; | |
[SerializeField] private LayerMask player; | |
// Start is called before the first frame update | |
void Start() | |
{ | |
rigidBodyComp = GetComponent<Rigidbody2D>(); | |
initialPos = transform.position.x; | |
currentPos = transform.position.x; | |
anim = GetComponent<Animator>(); | |
Physics2D.queriesStartInColliders = false; | |
} | |
private void FixedUpdate() | |
{ | |
transform.Translate(dir * speed * Time.deltaTime); | |
if (transform.position.x >= RightEnd) | |
{ | |
dir = Vector2.left; | |
transform.localScale = sizeLeft;// new Vector2(-4f, 4.6f); | |
RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.left,50f,player); | |
if(hit.collider != null) // && hit.collider.tag == "Player" | |
{ | |
Debug.Log("Hitted !!!! " + hit.collider.gameObject.tag); // NOT HITTING PLAYER | |
Debug.Log("Ray of "+gameObject.name+" Hits: " + hit.transform.name ); // NOT HITTING PLAYER | |
} | |
} | |
else if (transform.position.x <= leftEnd) | |
{ | |
dir = Vector2.right; | |
transform.localScale = sizeRight; // new Vector2(4f, 4.6f); | |
RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.right, 50f); | |
if(hit.collider != null) // && hit.collider.tag == "Player" | |
{ | |
Debug.Log("Hitted !!!! " + hit.collider.gameObject.tag); | |
Debug.Log("Ray of "+gameObject.name+" Hits: " + hit.transform.name ); | |
} | |
} | |
} | |
private void OnTriggerEnter2D(Collider2D collision) | |
{ | |
if (collision.tag == "Bullet") | |
{ | |
anim.SetTrigger("die"); | |
} | |
} | |
private void Deactivate() | |
{ | |
gameObject.SetActive(false); | |
Debug.Log("dying"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment