Random movement of enemy and collision with tilemap collider

Hello, I am trying to create an enemy with random movement and stop moving (or change direction) when collide with Tilemap collider. I created this script, enemy randomly moving, but still bypassing colliders(water).

public float speed;
    private Rigidbody2D rb;
    private float currenttime = 0;
    public float x;
    public float y;
    Vector2 randomdir;

    public void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    public void FixedUpdate()
    {
        currenttime += Time.fixedDeltaTime;
        if(currenttime > 2)
        {
            x = Random.Range(-1f, 1f);
            y = Random.Range(-1f, 1f);
            randomdir = new Vector2(x,y);
           

            currenttime = 0;
        }

        rb.velocity = new Vector2(x, y) * speed;

    }

Thank You for the answers.

The above code does nothing with colliders, so it works just fine setting velocity.

The problem has to be somewhere else, such as perhaps your colliders.

Do you have a collider on this actual patrol dude as well? He needs one or he’ll happily go through other colliders.

I also notice that you are setting but not using randomDir… I think you intended to use it on line 26 above.

Thanks, that was from last try (randomDir), and i am sorry, but what do you mean by patrol Dude ?

I mean this enemy. Does he have a collider?

Yes, everything works now, Thank You for your time.

1 Like