- Home /
How to create a simple enemy that moves vertically up and down
Hi all,
I am a student who has to create a simple game as part of an assignment. I really need help in creating and scripting an enemy that will move up and down causing difficulty for the player to jump from one platform to another. I know it may be a simple request but so far I cannot find any help online. I really would appreciate any help thanks
Answer by lordlycastle · Apr 02, 2015 at 10:09 PM
You really should be doing your homework on your own. But who am I to judge, I never did mine.
float maxMoveDistance = 10;
//Set this to your objects initial position when game starts.
Vector3 origin;
float speed = 10;
void Update(){
Vector3 destination = origin;
destination.y = (transform.position.y > origin.y + maxMoveDistance) ? origin.y : origin.y + maxMoveDistance;
transform.position = Vector3.MoveTowards(transform.position, destination, speed * Time.deltaTime);
}
Thanks Lordlycastle.
I set that up and you have it nearly spot on which I really appreciate. One problem I get is that the enemy instantly fly's over to my player on starting the game. How do i set the enemy up that they do not rush over to the player and just stay at various stages of the level where jumping from platform to platform takes place.
@steviemelts I think it’s because you didn’t set the origin to a value so it defaults to Vector3.zero, and I’m guessing that’s where your player is. In the Awake or Start function set the origin to the transforms position. This way it’ll remember it’s start position. Also I made a mistake in the second line, it should be destination.y = … and not *=. I’ll fix it now.
If you did, can you post your movement code. Don’t forget to use @ symbol with my name otherwise I won’t be notified.
@steviemelts Don’t forget to accept the answer if it answered the question.
Answer by tanoshimi · Apr 05, 2015 at 07:46 PM
An alternative using MathF.PingPong:
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour {
Vector3 _startingPos;
Transform _trans;
void Start() {
_trans = GetComponent<Transform>();
_startingPos = _trans.position;
}
void Update() {
_trans.position = new Vector3(_startingPos.x, _startingPos.y + Mathf.PingPong(Time.time, 3), _startingPos.z);
}
}
Your answer
Follow this Question
Related Questions
aquarium effect for 2d fish 2 Answers
2D Top-Down Movement: Transform.up and right don't change 2 Answers
How to I get my 2d gameobject to move towards another gameobject when it is clicked? 0 Answers
Help Wanted. Switching localscale starts unwanted animation state. 1 Answer
How can I make 2D movement less jerky on a controller, with velocity and such? 0 Answers