Last active
November 30, 2016 23:11
-
-
Save grimmdev/8620aafd37b07aab26e4 to your computer and use it in GitHub Desktop.
Detect edges for a simple moving enemy controller and apply movement
This file contains hidden or 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; | |
public class 2DEnemyController : MonoBehaviour { | |
// should we flip our enemy? | |
public bool isFlipped = false; | |
// used for Rotation | |
private Vector3 r = Vector3.zero; | |
// Update is called once per frame | |
void FixedUpdate(){ | |
// if we hit the left edge | |
if( !leftCheck() ) | |
{ | |
// flip the sprite | |
isFlipped = false; | |
} | |
// do we hit the right edge? | |
if( !rightCheck() ) | |
{ | |
// flip it back! | |
isFlipped = true; | |
} | |
// keep the enemy moving at a speed horizontally | |
gameObject.transform.Translate(0.01f,0,0); | |
// now we actually flip stuff with euler angles.. not as messy. | |
if( isFlipped ) | |
{ | |
r.y = 180; | |
} | |
else | |
{ | |
r.y = 0; | |
} | |
gameObject.transform.eulerAngles = r; | |
} | |
// simple bool function to check left edge of feet | |
bool leftCheck() | |
{ | |
float extraRayLength = 0.1f; | |
float extraRayWidth = 0.02f; | |
Vector3 startOfRay = gameObject.transform.position; | |
Vector3 lstartOfRay = startOfRay+(Vector3.left* (extraRayWidth + gameObject.collider2D.bounds.size.y/2.0f)); | |
Vector3 endOfRay = gameObject.transform.position - (Vector3.up* (extraRayLength + gameObject.collider2D.bounds.size.y/2.0f) ); | |
Vector3 lendOfRay = endOfRay + (Vector3.left* (extraRayWidth + gameObject.collider2D.bounds.size.y/2.0f)); | |
Debug.DrawLine( lstartOfRay, lendOfRay, Color.blue ); | |
RaycastHit2D hitLeft = Physics2D.Linecast( lstartOfRay, lendOfRay, 1 << LayerMask.NameToLayer( "Ground" ) ); | |
return hitLeft; | |
} | |
// now let's do it for the right side | |
bool rightCheck() | |
{ | |
float extraRayLength = 0.1f; | |
float extraRayWidth = 0.02f; | |
Vector3 startOfRay = gameObject.transform.position; | |
Vector3 rstartOfRay = startOfRay-(Vector3.left* (extraRayWidth + gameObject.collider2D.bounds.size.y/2.0f)); | |
Vector3 endOfRay = gameObject.transform.position - (Vector3.up* (extraRayLength + gameObject.collider2D.bounds.size.y/2.0f) ); | |
Vector3 rendOfRay = endOfRay - (Vector3.left* (extraRayWidth + gameObject.collider2D.bounds.size.y/2.0f)); | |
Debug.DrawLine( rstartOfRay, rendOfRay, Color.red ); | |
RaycastHit2D hitRight = Physics2D.Linecast( rstartOfRay, rendOfRay, 1 << LayerMask.NameToLayer( "Ground" ) ); | |
return hitRight; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment