Reputation: 55
So im trying to make an enemy AI which detects a player with the unity raycaster. The AI is, while working, detecting the player even if its miles further away than I would like. Could you help me?
also I'm getting a Rigidbody2D
and a player target. The seeDistance
is 2
code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class enemyMove : MonoBehaviour
{
public int speed;
private bool movingRight = true;
public bool SeenPlayer = false;
public Transform target;
public float seeDistance;
public int health = 3;
public Rigidbody2D rb;
public Transform groundDetection;
void Start()
{
target = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
if (SeenPlayer == false)
{
transform.Translate(Vector2.right * speed * Time.deltaTime);
}
else
{
transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
transform.localScale = new Vector3(0.5f, 0.5f, 0.5f);
}
RaycastHit2D groundInfo = Physics2D.Raycast(groundDetection.position, Vector2.down, 2f);
RaycastHit2D SeePlayer = Physics2D.Raycast(groundDetection.position, Vector2.left, seeDistance);
if (groundInfo.collider == false)
{
if (movingRight == true)
{
transform.eulerAngles = new Vector3(0, -180, 0);
movingRight = false;
}
else
{
transform.eulerAngles = new Vector3(0, 0, 0);
movingRight = true;
}
}
if (SeePlayer)
{
SeenPlayer = true;
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
BulletScript bullet = collision.GetComponent<BulletScript>();
if (bullet != null)
{
//Destroy(gameObject);-
health -= 1;
Destroy(bullet.gameObject);
if (health == 0)
{
Destroy(gameObject);
}
else
{
rb.AddForce(new Vector2(4, 2), ForceMode2D.Impulse);
}
}
}
}
Upvotes: 0
Views: 55
Reputation: 830
The problem is in:
if(SeePlayer){
SeenPlayer = true;
}
SeePlayer is of type RaycastHit2D (a struct). Struct is never null so the condition
if(SeePlayer)
is always meet. You should probably check if the collider inside is valid:
if(SeePlayer.collider)
EDIT: I suppose
if(SeePlayer != default(RaycastHit2D))
Would do the job too
Upvotes: 1