Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class enemyMoving : MonoBehaviour
- {
- // Rigidbody reference
- private Rigidbody2D rb2d;
- // moveSpeed of the enemy, edit in inspector
- [SerializeField] private float moveSpeed;
- // check distance, edit in inspector
- [SerializeField] private float distance;
- // change in inspector to see changes
- [SerializeField] private Vector2 checkOffset;
- // the ray origin
- Vector2 checkPosition;
- // direction of the enemy
- // 1 = right
- // -1 = left
- float direction = 1;
- void Start()
- {
- rb2d = GetComponent<Rigidbody2D>();
- }
- private void FixedUpdate()
- {
- direction = Mathf.Sign(moveSpeed);
- checkPosition = new Vector2(transform.position.x + checkOffset.x * direction,
- transform.position.y + checkOffset.y);
- RaycastHit2D hitInfo = Physics2D.Raycast(checkPosition, Vector2.down, distance);
- if (hitInfo.collider == null)
- {
- moveSpeed *= -1;
- transform.localScale = new Vector2(Mathf.Sign(moveSpeed), 1);
- }
- rb2d.velocity = new Vector2(moveSpeed, rb2d.velocity.y);
- }
- private void OnDrawGizmos()
- {
- Gizmos.color = Color.red;
- Gizmos.DrawLine(new Vector2(transform.position.x + checkOffset.x * direction, transform.position.y + checkOffset.y),
- new Vector2(transform.position.x + checkOffset.x * direction, (transform.position.y + checkOffset.y) - distance));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement