Move enemy to a specific movepoint with an array (C#)
Hello once again my fellow Unities, I'm trying to make an enemy move to a specific point on my map. I call the points "movepoints" and I set five points as Transform in an array. Now when the enemy spawn, the enemy is supposed to choose between one of these five points to go to. Right now when I start the the game the enemy is "glitching"/shaking trying to move to all points that I've placed, makes for some fun seizure moment but more to the point.
How can I make the enemy choose between one of these movepoints and move towards it? You guys are the best, the Unity community rules!
Here's the code for moving between the movepoints:
using UnityEngine;
using System.Collections;
public class EnemyExplodeScript : MonoBehaviour {
public Transform[] moveToPoints;
public float speed;
void Start ()
{
Physics2D.IgnoreLayerCollision (9, 10);
}
void Update ()
{
//Set where the enemy should go with random
int movePoint = Random.Range(0, moveToPoints.Length);
// Speed and time
float step = speed * Time.deltaTime;
// Get the enemy moving!
transform.Translate (Vector3.MoveTowards (transform.position, moveToPoints[movePoint].position, step) - transform.position);
}
}
Answer by allenallenallen · Mar 18, 2016 at 02:48 PM
You're getting a new random movePoint every frame. That's the problem.
int movePoint = 0;
void Start(){
Physics2D.IgnoreLayerCollision (9, 10);
movePoint = Random.Range(0, moveToPoints.Length);
}
By declaring the movePoint variable outside and setting it in Start(), the enemy will choose only one of the points and move toward it.
Your answer
Follow this Question
Related Questions
Something is wrong with my max. speed code 0 Answers
Instantiate spawn problem 1 Answer
C# movement code with the maximum movement speed. 1 Answer