Created
September 4, 2019 15:10
-
-
Save Ratstail91/4340551473f670bf8bb9649b6c26776d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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