i have an enemy that i want to change direction when it hits a wall to a random direction. i havnt coded in 2d in like 2 years and im not that good at code in general but im not sure whats happening. it simply wont collide no matter how i troubleshoot it.
supposed to call a random direction when collision happens but i cant get it to collide i dont know why and i cant find a solution.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class enemyMovement : MonoBehaviour {
public float moveForce = 0f;
private Rigidbody2D rbody;
public Vector2 moveDir;
// Use this for initialization
void Start () {
rbody = GetComponent ();
moveDir = ChooseDirection ();
}
void OnCollisionEnter2d(Collision2D coll)
{
if (coll.gameObject.tag == “walls”) {
//moveDir = ChooseDirection ();
Debug.Log (“bang”);
}
}
// Update is called once per frame
void Update () {
rbody.velocity = moveDir * moveForce;
}
Vector2 ChooseDirection()
{
System.Random ran = new System.Random ();
int i = ran.Next (0, 3);
Vector2 temp = new Vector2 ();
if (i == 0)
{
temp = transform.up;
}
if (i == 1)
{
temp = -transform.up;
}
if (i == 2)
{
temp = transform.right;
}
if (i == 3)
{
temp = -transform.right;
}
return temp;
}
}
i modified a script that was meant for 2d and supposed to cast a raytrace from the player direction and when the walls were closer that 5 units it would change direction but since this is in 2d i changed it to be a simple collision and the vector3s to vector2s. im not really sure where to go from here but it compiles and runs it just wont detect the collision.
thanks in advance!