Please help with 2d 8 way random enemy movement within a range
Hi I am new to unity having and having a hard time finding info on this exact problem. I was thinking of using an array so I can do right+up diagonals for example but cannot figure out how to keep the monsters within a range if I use one. There's some code I really like but I'm having a hard time putting it together properly and am not sure it's even compatible. Here is the part I want to use instead of the random angles..
Vector2[] moveDirections = new Vector2[] { Vector2.right, Vector2.left, Vector2.up, Vector2.down, Vector2.right + Vector2.down, Vector2.left + Vector2.down, Vector2.left + Vector2.up, Vector2.right + Vector2.up };
This is the best code I could find but it doesn't have the exact angles or include rigidbodies (you need these for when enemies are hit right?) and I'm not sure I can use the array with it. I might just use it if I have to.. It used to have $$ Symbols that I changed because I cannot get unity to work otherwise..
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Enemy : MonoBehaviour { public float waitTime = 2f; public float directionChangeTime = 3f;
private float latestDirectionChangeTime;
private float characterVelocity = 10f;
private Vector2 movementDirection;
private Vector2 movementPerSecond;
private bool isWaiting;
int minX = -8;
int maxX = 8;
int minY = -4;
int maxY = 4;
protected void Start()
{
isWaiting = false;
latestDirectionChangeTime = 0f;
CalcuateNewAnonymousMovementVector();
}
protected void Update()
{
if (Time.time - latestDirectionChangeTime > directionChangeTime && !isWaiting)
{
isWaiting = true;
Invoke("InvokeIsWaiting", waitTime);
movementPerSecond = Vector3.zero;
}
//move enemy:
transform.position = new Vector2(transform.position.x + (movementPerSecond.x * Time.deltaTime),
transform.position.y + (movementPerSecond.y * Time.deltaTime));
// This was really useful to keep stuff in the boundaries and not be stuck moving against the wall like with the clamp so would really like to keep it if possible..
if (transform.position.x < minX || transform.position.x > maxX) movementPerSecond.x = -movementPerSecond.x;
if (transform.position.y < minY || transform.position.y > maxY) movementPerSecond.y = -movementPerSecond.y;
}
void InvokeIsWaiting()
{
latestDirectionChangeTime = Time.time;
CalcuateNewAnonymousMovementVector();
isWaiting = false;
}
void CalcuateNewAnonymousMovementVector()
{
movementDirection = new Vector2(UnityEngine.Random.Range(-1.0f, 1.0f), UnityEngine.Random.Range(-1.0f, 1.0f)).normalized;
movementPerSecond = movementDirection * characterVelocity;
}
}