1
\$\begingroup\$

Ok, so in my Java2D Game, using swing/awt (I hear it is not the best to combine those), I am trying to finish collisions.


So, the problem is, the "if (player.xvel < 0) { }" and the "if (player.xvel > 0) { }" in the Block class are still being executed even though the player hasn't run into the block horizontally. How can I make it so the code is executed when the player runs/walks into the block horizontally?

My code for the collide function is below, in Block.java:

    void collide(Player player) {  
        Rectangle player_hb = new Rectangle((int) player.x, (int) player.y, (int) player.width, (int) player.height);
        Rectangle block_hb = new Rectangle(x + Display.graphics_panel.WorldX, y, width, height);

        if (player_hb.intersects(block_hb)) {
            Rectangle intersection = (Rectangle) player_hb.createIntersection(block_hb);  

            if (player.yvel > 0) {
                player.jumping = false;
                player.y -= intersection.getHeight();
            }
            if (player.yvel < 0) {
                player.yvel = 0;
                player.y += intersection.getHeight(); 
            }
            /* Execute this code ONLY if player is intersecting a block HORIZONTALLY!! */
            if (player.xvel > 0) {
                System.out.println("You shouldn't see this unless you run into a block!" + i++);
            }
            if (player.xvel < 0) {
                System.out.println("You shouldn't see this unless you run into a block!" + i--);
            }
        }
    }   
\$\endgroup\$
4
  • \$\begingroup\$ Also, should I be moving the world, or the player/camera. Right now I am moving the world as I do not know how to make a camera. \$\endgroup\$
    – shepgoba
    Commented Jan 17, 2017 at 4:37
  • 1
    \$\begingroup\$ The camera is stationary, people usually move the world through the camera using matrices. \$\endgroup\$
    – Bálint
    Commented Jan 17, 2017 at 10:15
  • \$\begingroup\$ Is all of that code relevant? If not please only provide the relevant code for us to see. It becomes tedious solving your issue if we have to filter irrelevant code at the same time. \$\endgroup\$
    – Charanor
    Commented Jan 17, 2017 at 14:44
  • \$\begingroup\$ sorry, I will link the relevant code, and I do not know what matrices are \$\endgroup\$
    – shepgoba
    Commented Jan 17, 2017 at 17:44

1 Answer 1

1
\$\begingroup\$

Ok, I finally found the solution! I made a hitbox for the x-axis so the x wouldn't interfere with the y. (by subtracting 10 from the y and 20 from the height) Now collisions are working abosolutely perfect!

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .