Advertisement
Guest User

Untitled

a guest
Sep 15th, 2019
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.55 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class enemyMoving : MonoBehaviour
  6. {
  7.     // Rigidbody reference
  8.     private Rigidbody2D rb2d;
  9.  
  10.     // moveSpeed of the enemy, edit in inspector
  11.     [SerializeField] private float moveSpeed;
  12.     // check distance, edit in inspector
  13.     [SerializeField] private float distance;
  14.     // change in inspector to see changes
  15.     [SerializeField] private Vector2 checkOffset;
  16.  
  17.     // the ray origin
  18.     Vector2 checkPosition;
  19.     // direction of the enemy
  20.     // 1 = right
  21.     // -1 = left
  22.     float direction = 1;
  23.  
  24.     void Start()
  25.     {
  26.         rb2d = GetComponent<Rigidbody2D>();
  27.     }
  28.  
  29.     private void FixedUpdate()
  30.     {
  31.         direction = Mathf.Sign(moveSpeed);
  32.         checkPosition = new Vector2(transform.position.x + checkOffset.x * direction,
  33.             transform.position.y + checkOffset.y);
  34.  
  35.         RaycastHit2D hitInfo = Physics2D.Raycast(checkPosition, Vector2.down, distance);
  36.         if (hitInfo.collider == null)
  37.         {
  38.             moveSpeed *= -1;
  39.             transform.localScale = new Vector2(Mathf.Sign(moveSpeed), 1);
  40.         }
  41.         rb2d.velocity = new Vector2(moveSpeed, rb2d.velocity.y);
  42.     }
  43.  
  44.     private void OnDrawGizmos()
  45.     {
  46.         Gizmos.color = Color.red;
  47.         Gizmos.DrawLine(new Vector2(transform.position.x + checkOffset.x * direction, transform.position.y + checkOffset.y),
  48.             new Vector2(transform.position.x + checkOffset.x * direction, (transform.position.y + checkOffset.y) - distance));
  49.     }
  50.  
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement