Skip to content

Instantly share code, notes, and snippets.

@Ratstail91
Created September 4, 2019 15:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ratstail91/4340551473f670bf8bb9649b6c26776d to your computer and use it in GitHub Desktop.
Save Ratstail91/4340551473f670bf8bb9649b6c26776d to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyController : MonoBehaviour {
//structures
enum Direction {
UP, LEFT, RIGHT, DOWN,
};
enum Behaviour { //NOTE: These need better names than just "first" and "second"
FIRST, //move up/down at targetX
SECOND, //move towards and stay at target Y
};
//members
public Vector2 moveSpeed = new Vector2(200, 200); //NOTE: doesn't HAVE to be a vector
public Vector2 target = new Vector2(3, 3); //NOTE: doesn't HAVE to be a vector
public Direction direction = Direction.LEFT;
public Behaviour behaviour = Behaviour.FIRST;
//behaviour parameters
public bool moveUp = true;
//components
Rigidbody2D rb;
void Awake() {
rb = GetComponent<Rigidbody2D>();
}
void FixedUpdate() {
HandleMovement();
}
void OnBecameInvisible() {
//cleanup
Destroy(gameObject);
}
//movement control
void HandleMovement() {
switch(behaviour) {
case Behaviour.FIRST:
HandleFirstBehaviour();
break;
case Behaviour.SECOND:
HandleSecondBehaviour();
break;
}
}
void HandleFirstBehaviour() {
//if passed target.x, move up/down
Vector2 velocity = new Vector2(-moveSpeed.x, 0);
if (rb.position.x < target.x) {
velocity.y = moveSpeed.y * (moveUp ? 1 : -1);
}
rb.velocity = velocity;
}
void HandleSecondBehaviour() {
//if not at target.y, move towards target.y
Vector2 velocity = new Vector2(-moveSpeed.x, 0);
if (rb.position.y < target.y && moveUp) {
velocity.y = moveSpeed.y;
}
if (rb.position.y > target.y && !moveUp) {
velocity.y = -moveSpeed.y;
}
rb.velocity = velocity;
}
//NOTE: could add more functions down here for different directions
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment