I have two squares drawn on the screen, how can I detect collision on the edges of both objects?

前端 未结 3 1003
天命终不由人
天命终不由人 2021-01-29 11:36

Right now, I can compare the X and Y to check for collision, but that\'s only if the two objects pass right through each other, on exactly the same X & Y pos. I need to chec

3条回答
  •  生来不讨喜
    2021-01-29 12:07

    Elist was/is a huge help! However I found this created a large square around my first square and messed up the collisions. Here is my implementation based off of Elist's post.

    public boolean colliding(Square os)
    {
        // the lesser value is the distance of the square's width and that of the lenght of the
        // other square
        return Math.abs(center.x - os.center.x) < width / 2 + os.width / 2 
                && Math.abs(center.y - os.center.y) < height / 2 + os.width / 2;
    }
    

    All due respect to Elist, I would not have come to this conclusion without their post.

    Additional help for those interested would be a handler that can stop the incoming square, and one that reflects it based on the other squares velocity.

    // stops the square from intersecting
    public void push_collided_basic(Square os, float refelct_amnt)
    {
        if(os.center.x < center.x)
            os.center.x -= refelct_amnt;
        else if(os.center.x > center.x)
            os.center.x += refelct_amnt;
        if(os.center.y < center.y)
            os.center.y -= refelct_amnt;
        else if(os.center.y > center.y)
            os.center.y += refelct_amnt;
    }
    
    // and now one that reflects the ball -> untested!!!
    public void push_collided_velocity(Square os)
    {
        // flip the velocitys directions for x
        if(os.center.x < center.x 
                  || os.center.x > center.x)
                 os.vel_x *= -1;
    
         // flip the velocity direction for y
        if(os.center.y < center.y
                  || os.center.y > center.y)
                 os.vel_y *= -1;
    
          // update the coordiantes
          os.center.x += vel_x;
          os.center.y += vel_y;
    }
    

提交回复
热议问题