Advertisement
Guest User

Untitled

a guest
Jan 19th, 2020
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.69 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class EnemyPatrol : Enemy
  5. {
  6.     public LayerMask enemyMask;
  7.     public float speed = 1;
  8.     Rigidbody2D myBody;
  9.     Transform myTrans;
  10.     float myWidth, myHeight;
  11.  
  12.     protected override void Start() {
  13.         base.Start();
  14.         myTrans = this.transform;
  15.         myBody = this.GetComponent<Rigidbody2D>();
  16.         SpriteRenderer mySprite = this.GetComponent<SpriteRenderer>();
  17.         myWidth = mySprite.bounds.extents.x;
  18.         myHeight = mySprite.bounds.extents.y;
  19.     }
  20.  
  21.     void FixedUpdate () {
  22.  
  23.         //Use this position to cast the isGrounded/isBlocked lines from
  24.         Vector2 lineCastPos = myTrans.position.toVector2() - myTrans.right.toVector2() * myWidth + Vector2.up * myHeight;
  25.         //Check to see if there's ground in front of us before moving forward
  26.         Debug.DrawLine(lineCastPos, lineCastPos + Vector2.down);
  27.         bool isGrounded = Physics2D.Linecast(lineCastPos, lineCastPos + Vector2.down, enemyMask);
  28.         //Check to see if there's a wall in front of us before moving forward
  29.         Debug.DrawLine(lineCastPos, lineCastPos - myTrans.right.toVector2() * .05f);
  30.         bool isBlocked = Physics2D.Linecast(lineCastPos, lineCastPos - myTrans.right.toVector2() * .05f, enemyMask);
  31.  
  32.         //If theres no ground, turn around. Or if I hit a wall, turn around
  33.         if(!isGrounded || isBlocked) {
  34.             Vector3 currRot = myTrans.eulerAngles;
  35.             currRot.y += 180;
  36.             myTrans.eulerAngles = currRot;
  37.         }
  38.  
  39.         //Always move forward
  40.         Vector2 myVel = myBody.velocity;
  41.         myVel.x = -myTrans.right.x * speed;
  42.         myBody.velocity = myVel;
  43.  
  44.     }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement