I am not very good at programming and in general math since I recently began to study this industry . I need help developing my own game . The game itself is 2D. I do not know how to make the boundaries of the desired objects. So let's say Hitbox . The problem itself: to describe these boundaries of objects in the consequence, so that they could come into contact with each other and execute a certain part of the code. For example, cause damage or stop the movement of these objects. Please explain exactly how to do this and how the Hitbox is created and how to extract the necessary data for comparison, " Did this object touch with another object or not? " Thank you in advance for your advice and assistance.

    1 answer 1

    This is called a collision, for example, you can simply create a class CollisionRect whose objects will accept x and y and in this class there will be a method (ColidesWith for example) that checks the collision of two objects in x and y, the width and height of objects. It sounds hard, but actually very simple. I'm just doing a 2D game on java on libgdx, here's an example of the code for this class CollisionRect:

    package com.imaginegames.mmgame.tools; public class CollisionRect { float x, y, width, height; public CollisionRect(float x, float y, float width, float height) { this.x = x; this.y = y; this.width = width; this.height = height; } public void move (float x, float y) { this.x = x; this.y = y; } public boolean CollidesWith (CollisionRect rect) { return x < rect.x + rect.width && y < rect.y + rect.height && x + width > rect.x && y + height > rect.y; } } 

    But already during the game it is checked for a collision of a fireball and a rocket that destroys this fireball, a rocket - bullet:

     for (Bullet bullet : bullets) { for (Fireball fireball : fireballs) { if (bullet.getCollisionRect().CollidesWith(fireball.getCollisionRect())) { fireballs_to_remove.add(fireball); bullets_to_remove.add(bullet); explosions.add(new Explosion(bullet.x, fireball.x, Bullet.WIDTH, Fireball.WIDTH, bullet.y, fireball.y, Bullet.HEIGHT, Fireball.HEIGHT, 0.5f)); } } } 

    Here on YouTube video , libgdx is true, but as you can see CollisionRect does not use libgdx libraries.

    I hope I helped, if you don’t understand something - paint to help, just try to draw the square of the first body and the second one and you will understand that the cycle in ColidesWith works in any case, bodies 1 and 2 or 2 and 1 meet, no matter which way.

    And if briefly: object borders are X objects and X + Width and Y and Y + Height Damage - just if true is checked when two objects are in contact, for example, health decreases by 20 In general, see the lesson, I hope you know English .