- Home /
Make enemy move up and down by itself in 2D space?
Well the question says it all pretty much. So if you have played the Mario games, there is a turtle that flies up and down making it difficult for Mario to get through. Well that is what I am trying to accomplish, for the enemy to move up and down. As of right now, I have a way-point script that accomplishes this but I don't want to make several game objects for the enemies to follow. If I could set the position that the enemy would move to in the inspector that would be great. An example being, set the distance that the enemy has to move is 3 units up and then 3 units down, and it repeats. Thanks!
Answer by Captain_Pineapple · Apr 26, 2018 at 07:19 PM
If you want the effect of a "Mario-turtle" that should be pretty simple. Assuming that you have some Vector3 with your starting position:
public void Update()
{
transform.position = startingPosition + Vector3.up * Mathf.Sin(Time.realtimeSinceStartup) * maxDistanceFromStart;
}
If this is not enough and you need a linear movement please comment below.
Hey @Captain_Pineapple thanks for your script, it works pretty well. One thing that I would like to comment on is how to get "maxDistanceFromStart" to not be the speed that the object has to travel? According to what you put, if I set the maxDistanceFromStart to 5, it travels slower than if I were to set it to 10. how would I make it go 5 units up and down but at different speeds without having to change how many units it moves? What I did, is that I made a public Vector 3 named startingPosition and set those coordinates, and then I made a public int named maxDistanceFromStart and that is how I got what you gave me to work. Thanks a bunch!
Answer by SBrooks75 · May 08, 2018 at 03:43 PM
Hey @AlejandroBoss10 , this script should give you something similar to what your looking for. I tested it. If you have questions setting it up in inspector let me know.
public Vector3 startPosition;
public Vector3[] moveToPoints;
public Vector3 currentPoint;
public float moveSpeed;
public int pointSelection;
// Use this for initialization
void Start () {
//Sets the object to your starting point
this.transform.position = startPosition;
}
// Update is called once per frame
void Update () {
Move ();
}
void Move(){
//Starts to move the object towards the first "moveToPoint" you set in inspector
this.transform.position = Vector3.MoveTowards (this.transform.position, currentPoint, Time.deltaTime * moveSpeed);
//check to see if the object is at the next "moveToPoint"
if (this.transform.position == currentPoint) {
//if so it sets the next moveTo location
pointSelection++;
//if your object hits the last "moveToPoint it sends the object back to starting position to start the sequence over
if (pointSelection == moveToPoints.Length){
pointSelection = 0;
}
//sets the destination of the "moveToPoint" destination
currentPoint = moveToPoints[pointSelection];
}
}