Created
July 16, 2014 17:44
-
-
Save ZeronSix/092953d7f8673227a590 to your computer and use it in GitHub Desktop.
Very dumb AI
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 UnityEngine; | |
using System.Collections; | |
using Pathfinding; | |
// WARNING: BYDLOCODE!!!!! | |
public class EnemyController : MonoBehaviour | |
{ | |
public Path path; | |
public float moveSpeed; | |
public float nextWaypointDistance = 0.5f; | |
Seeker seeker; | |
GameObject player; | |
Animator anim; | |
int currentWaypoint = 0; | |
Vector2 desiredVelocity = Vector2.zero; | |
void Start() | |
{ | |
seeker = GetComponent<Seeker>(); | |
player = GameObject.FindGameObjectWithTag("Player"); | |
anim = GetComponent<Animator>(); | |
RestartPath(); | |
} | |
void FixedUpdate() | |
{ | |
if (path == null || currentWaypoint >= path.vectorPath.Count) | |
{ | |
//rigidbody2D.velocity = Vector2.zero; | |
return; | |
} | |
rigidbody2D.velocity = desiredVelocity; | |
anim.SetFloat("Speed", rigidbody2D.velocity.magnitude); | |
if (Vector3.Distance(transform.position, path.vectorPath[currentWaypoint]) < nextWaypointDistance) | |
{ | |
currentWaypoint++; | |
return; | |
} | |
} | |
void RestartPath() | |
{ | |
seeker.StartPath(transform.position, player.transform.position, OnPathComplete); | |
} | |
void UpdateVelocity() | |
{ | |
if (currentWaypoint > path.vectorPath.Count - 1) | |
{ | |
desiredVelocity = Vector2.zero; | |
return; | |
} | |
Vector2 vel = (path.vectorPath[currentWaypoint + 1] - transform.position).normalized; | |
vel *= moveSpeed * Time.deltaTime; | |
desiredVelocity = vel; | |
Vector3 scale = transform.localScale; | |
scale.x = Mathf.Sign(desiredVelocity.x); | |
transform.localScale = scale; | |
} | |
void OnPathComplete(Path p) | |
{ | |
currentWaypoint = 0; | |
if (!p.error) | |
path = p; | |
UpdateVelocity(); | |
RestartPath(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment