Change Collision HitBox size with Pygame
In this module, we are going to learn how to Change Collision HitBox size with Pygame in Python. i.e, if two characters have collided we can make the collision possible using a rectangular box around the character. When this box of character collided with another box of character.we could say collision has occurred.
Implement Hitbox with Rectangle using Pygame
Here we are drawing a rectangle around the character so that when rectangle collides with another rectangle we could say that collision has occurred. First, let us draw a line onto our screen you can take any shape like an ellipse, polygon, image character, etc. and draw a rectangle around the taken object.
The following code describes drawing a line with HitBox as follows
import pygame import sys pygame.init() disp_surf=pygame.display.set_mode((500,400)) pygame.display.set_caption("Hit box") Red=(255,0,0) Green=(0,255,0) disp_surf.fill((255,255,255)) pygame.draw.line(disp_surf,Green,(32,120),(120,120),15) hit_box = (27,103,98,38) pygame.draw.rect(disp_surf,Red,hit_box,2) while True: for eve in pygame.event.get(): if eve.type==pygame.QUIT: pygame.quit() sys.exit() pygame.display.update()
When we execute the above code we get a line to green in color of size 15 and a rectangle around the line. (32,120) represents (x,y) coordinate start point of the line. similarly (120,120) represent (x,y) coordinate endpoint of line.
How to Change Collision HitBox size with Pygame in Python
Now let us understand about hit_box used. we are using these two lines to include HitBox as follows
pygame.draw.rect(surface object,color,hit_box,width of rectangular lines)
Here, x,y represents the position of the rectangle concerning the object we have drawn and width, height represents the dimensions to cover that object. With the help of pygame.draw.rect() we can draw a rectangle around our object.
To change the rectangular size you can change the hit_box parameters as follows
hit_box = (22,98,105,44)
The size of the box is increased as follows
We can modify the parameters mentioned above according to user knowledge to change the size.