This is my script for enemy direction , its just moving forwards and backward.
Don’t know why other rays are shattered too
strong text
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyMove : MonoBehaviour
{
public float enemySpeed;
enum Direction { FORWARD,BACKWARD,LEFT,RIGHT};
Direction currentDirection = Direction.LEFT;
bool directionSelected = false;
// Update is called once per frame
void Update()
{
if (directionSelected)
{
switch (currentDirection)
{
case Direction.LEFT:
gameObject.transform.position = gameObject.transform.position + Vector3.left * enemySpeed * Time.deltaTime;
break;
case Direction.RIGHT:
gameObject.transform.position = gameObject.transform.position + Vector3.right * enemySpeed * Time.deltaTime;
break;
case Direction.FORWARD:
gameObject.transform.position = gameObject.transform.position + Vector3.forward * enemySpeed * Time.deltaTime;
break;
case Direction.BACKWARD:
gameObject.transform.position = gameObject.transform.position + Vector3.back * enemySpeed * Time.deltaTime;
break;
}
}
}
private void OnCollisionEnter(Collision collision)
{
directionSelected = false;
Debug.DrawLine(gameObject.transform.position, Vector3.left * 5f, Color.red,1000f);
Debug.DrawLine(gameObject.transform.position, Vector3.right * 5f, Color.red, 1000f);
Debug.DrawLine(gameObject.transform.position, Vector3.forward * 5f, Color.red, 1000f);
Debug.DrawLine(gameObject.transform.position, Vector3.back * 5f, Color.red, 1000f);
while (!directionSelected)
{
Random.seed = System.DateTime.Now.Millisecond;
int checkDirection = Random.Range(1, 4);
Debug.Log(checkDirection);
switch (checkDirection)
{
case 1:
if (!Physics.Raycast(gameObject.transform.position, Vector3.left, 1f))
{
currentDirection = Direction.LEFT;
directionSelected = true;
}
break;
case 2:
if (!Physics.Raycast(gameObject.transform.position, Vector3.right, 1f))
{
currentDirection = Direction.RIGHT;
directionSelected = true;
}
break;
case 3:
if (!Physics.Raycast(gameObject.transform.position, Vector3.forward, 1f))
{
currentDirection = Direction.FORWARD;
directionSelected = true;
}
break;
case 4:
if (!Physics.Raycast(gameObject.transform.position, Vector3.back, 1f))
{
currentDirection = Direction.BACKWARD;
directionSelected = true;
}
break;
}
}
}
}