Advertisement
GoodNoodle

MoveableObject

Apr 14th, 2023 (edited)
906
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.17 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using UnityEngine;
  5.  
  6. public class MovableObject : MonoBehaviour
  7. {
  8.     public float speed;
  9.  
  10.     //public Transform target;
  11.  
  12.     public Vector2 velocity = Vector2.zero;
  13.  
  14.     public bool IsMoving;
  15.  
  16.     public bool canSlid = false;
  17.     //private void OnTriggerStay2D(Collider2D collision)
  18.     //{
  19.  
  20.        
  21.        // if ((collision.tag == "Player" || collision.tag == "Buddy") && Input.GetKeyDown(KeyCode.Z))
  22.        // {
  23.         //    if (collision.tag == "Block")
  24.          //   {
  25.           //      var collider = GameLayers.I.SolidLayer;
  26.           //      transform.position = Vector2.SmoothDamp(transform.position, target.position, ref velocity, speed * Time.deltaTime);
  27.           //  }
  28.  
  29.        // }
  30.     //}
  31.  
  32.     public IEnumerator Move(Vector2 moveVec)
  33.     {
  34.        
  35.         var targetPos = transform.position;
  36.         targetPos.x += moveVec.x;
  37.         targetPos.y += moveVec.y;
  38.  
  39.         //var ledge = CheckForLedge(targetPos);
  40.        // if (ledge != null)
  41.        // {
  42.        //     if (ledge.TryToJump(this, moveVec))
  43.        //         yield break;
  44.        // }
  45.  
  46.         if (!IsPathClear(targetPos))
  47.             yield break;
  48.  
  49.      
  50.         IsMoving = true;
  51.  
  52.         while ((targetPos - transform.position).sqrMagnitude > Mathf.Epsilon)
  53.         {
  54.             transform.position = Vector3.MoveTowards(transform.position, targetPos, speed * Time.deltaTime);
  55.             yield return null;
  56.         }
  57.         transform.position = targetPos;
  58.  
  59.         IsMoving = false;
  60.  
  61.         // check if done moving
  62.         //OnMoveOver?.Invoke();
  63.     }
  64.  
  65.     private bool IsPathClear(Vector3 targetPos)
  66.     {
  67.         var diff = targetPos - transform.position;
  68.         var dir = diff.normalized;
  69.  
  70.         var collisionLayer = GameLayers.I.SolidLayer | GameLayers.I.InteractableLayer | GameLayers.I.PlayerLayer;
  71.  
  72.         Debug.DrawLine(transform.position, targetPos, Color.magenta);
  73.        
  74.  
  75.         if (Physics2D.BoxCast(transform.position + dir, new Vector2(0.2f, 0.2f), 0f, dir, diff.magnitude - 1, collisionLayer) == true)
  76.             return false;
  77.  
  78.         return true;
  79.     }
  80.  
  81.  
  82.  
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement