Question by
Bartlers · Oct 08, 2019 at 11:41 AM ·
2drigidbody2ddirectionplatformermoving
Unity 2d random Enemy and random direction movement on spawn.
Hello everyone. So im stuck in 1 problem is on spawning enemies they always move in 1 direction and its left. I got 2 different scripts for moving and spawning. And i would like to know how to make on spawn move enemies in random direction. Here is moving script:
public class EnemyMover : MonoBehaviour
{
public float moveSpeed = 3;
public float maxSpeed = 1;
private Vector2 movement;
float direction;
Rigidbody2D rb;
public void Awake() // Get Main Components
{
rb = GetComponent<Rigidbody2D>();
}
private void Start() // To Get second Components
{
direction = Random.Range(-1, 1);
}
private void FixedUpdate()
{
float x = 1;
Vector2 movement = new Vector2(x * direction, 0);
rb.AddForce(movement * moveSpeed, ForceMode2D.Impulse);
if (rb.velocity.x > maxSpeed)
{
rb.velocity = new Vector2(maxSpeed, 0);
}
else if (rb.velocity.x < -maxSpeed)
{
rb.velocity = new Vector2(-maxSpeed, 0);
}
if(direction == 0)
{
direction = Random.Range(-1, 1);
}
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Direction")
{
direction = -direction;
}
}
}
Thanks for attention and help :)
Comment
And here is a simple spawning script.
void SpawnEnemy()
{
InstantiationTimer -= Time.deltaTime;
if (InstantiationTimer <= 0)
{
int i = Random.Range(0,Points.Length);
current = Points[i];
GameObject clone = (GameObject)Instantiate(Enemy, current.transform.position, Quaternion.identity);
InstantiationTimer = Random.Range(2, 5);
}
}