How to enable and disable mouse drag to avoid collision in unity 3d using C #

I have walls that block the player's movement in the scene. I want to drag the player when the path is clear and disconnect when the player hits the wall. I can enable and disable the mouseButtonDown () function. This is only allowed when the mouse is pressed. I do not want it.

if (Input.GetMouseButtonDown(0))
{
    if (enableDrag ==false)
        enableDrag = true;
}

OnMouseDrag()
{
    if(enableDrag== true)
    {
        ....
    }
}

.....

void OnCollisionEnter2D (Collision2D coll)
{
    if (coll.gameObject.tag == "Walls") 
    {
        enableDrag= false;
    }
}

      

Also, I don't want the player to move erratically when they hit a wall. Any comments from your experience are rude.

+3


source to share


2 answers


Why don't you change the logic. It looks like you want constant resistance as long as you don't hit a wall. So in this case, you can say:

Pseudo:

Inside your update ()



If (not colliding with walls) 
    DragObject()

      

This will require you to know when you no longer collide. It is possible to use OnCollisionExit.

0


source


While it's not too late to answer, here's how I solved the problem. With this approach, you can constantly drag and drop the player as it doesn't bump into obstacles.



void OnMouseOver ()
    {

    Vector2 mousePos;

    Vector3 mousePosWorld = Camera.main.ScreenToWorldPoint (Input.mousePosition);
        mousePos.x = mousePosWorld.x;
        mousePos.y = mousePosWorld.y;
        this.transform.position = Vector3.MoveTowards (transform.position, new Vector3 (mousePosWorld.x, mousePosWorld.y, 0), speed * Time.deltaTime);



        if (enableDrag) {

            Vector3 cursorPoint = new Vector3 (Input.mousePosition.x, Input.mousePosition.y, 0);
            Vector3 cursorPosition = Camera.main.ScreenToWorldPoint (cursorPoint) + offset;
            transform.position = new Vector3 (cursorPosition.x, cursorPosition.y, 0);



        }


If void OnCollisionEnter2D (Collision2D coll)
{
 if (coll.gameObject.tag == "Obstacle") 
 {
     enableDrag= false;
  }
}

      

0


source