Advertisement

How to stop a moving game object when reach position (0,0) 2D Game

Started by August 14, 2020 04:11 PM
3 comments, last by TheRottenCookie 4 years, 2 months ago

Hello!
I am beginnner in programming and Unity and I want to stop the Ceiling from moving up when reach position (0,0).

I dont know how to do it. I spent a lot of time to solve it. I tried to use vector and GameObject.

Please help!

PS. I made a square with box collider above ceiling to stop it but I want to learn how to do it

using UnityEngine;
using UnityEngine.Tilemaps;

public class CeilingMove : MonoBehaviour {
   [SerializeField] private LayerMask Ceilinglayermask;
   private Rigidbody2D rb2d;
   [SerializeField] private TilemapCollider2D TileCol2D;
   public float ceilingSpeedDown = 2.0f;
   public float ceilingSpeedUp = 2.0f;
   public float timeBeforeFall = 2.0f;
   public float timeBeforeUp = 6.0f;
   void Start() {
       rb2d = GetComponent<Rigidbody2D>();
   }
   void FixedUpdate() {
       Falling();
       Upwards();
   }
   private bool IsTouching() {
       RaycastHit2D RaycastHit2D = Physics2D.CapsuleCast(TileCol2D.bounds.center, TileCol2D.bounds.size, 0, 0f, Vector2.down, 0.1f, Ceilinglayermask);
       Debug.Log(RaycastHit2D.collider);
       return RaycastHit2D.collider == null;
   }
   public void Falling() {
       Vector2 CeilingFall = Vector2.down * ceilingSpeedDown;
       timeBeforeFall -= Time.fixedDeltaTime;
       if (timeBeforeFall <= 0 && IsTouching() == true) {
           rb2d.constraints = RigidbodyConstraints2D.None;
           rb2d.constraints = RigidbodyConstraints2D.FreezeRotation | RigidbodyConstraints2D.FreezePositionX;
           rb2d.AddForce(CeilingFall, ForceMode2D.Impulse);
           timeBeforeFall = 8;

       }
   }
   public void Upwards() {
       Vector2 CeilingUp = Vector2.up * ceilingSpeedUp;
       timeBeforeUp -= Time.fixedDeltaTime;
       if (timeBeforeUp <= 0 && transform.localPosition.y < 0) {
           rb2d.constraints = RigidbodyConstraints2D.None;
           rb2d.constraints = RigidbodyConstraints2D.FreezeRotation | 									RigidbodyConstraints2D.FreezePositionX;
           rb2d.AddForce(CeilingUp, ForceMode2D.Impulse);
           timeBeforeUp = 11;
       }
   }
}

Hi, yep, I've had such a problem too?

None

Advertisement

@ThomasJoseph Can you send me a message on discord? Maybe together we will do it. Discord: TheRottenCooki#6854

I did it.

This topic is closed to new replies.

Advertisement