K
K
Kapsamun Artem2022-01-10 12:02:14
Python
Kapsamun Artem, 2022-01-10 12:02:14

How to make collision between grenade and floor in pygame?

I want to make a grenade in the game but I don't know how to make it stay on the blocks.
using python with pygame library
61dbf7b4ce12e663721851.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
Fallerwood, 2022-01-10
@Fallerwood

The collision should not be between, but on the floor and on the grenade ..

I
Ivan Chetchasov, 2022-03-06
@TalismanChet

Good day.
Let's imagine the situation: the image of the grenade overlapped the image of the earth:
Let the Rect of the earth = Rect(0, 90, 100, 10) with a window of 100x100px
Case 1.
Let the x and y of the grenade be stored separately.
Then you need to create a new Rect with the coordinates of the grenade and the size of the desired hitbox. If you turn on the rendering of such a Rect , you can see the following picture:
6224b13196b27565859800.png
That is, this is the hitbox of the grenade.
Next, we need to take each hitbox point in the picture (this works well with small target and large checking hitboxes, if the ground was small and the grenade was huge, then the check would need to be done from the ground to the grenade and from the grenade to the ground) and compare overlap with ground hitbox:

groundRect.collidepoint(granadeRectPoint)
# True если перекрывается

And then you can perform the required actions, for example, destroy a copy of the grenade or reset its motion vector.
Case 2.
Let x and y of the grenade be equal to x and y of the image.
Then you need to extract the Rect with the coordinates of the grenade from the image:
granadeRect = granadeImage.get_rect()
If you turn on the rendering of such a Rect , you can see the following picture:
6224b13196b27565859800.png
That is, this is the hitbox of the grenade.
Next, we need to take each hitbox point in the picture (this works well with small target and large checking hitboxes, if the ground was small and the grenade was huge, then the check would need to be done from the ground to the grenade and from the grenade to the ground) and compare overlap with ground hitbox:
groundRect.collidepoint(granadeRectPoint)
# True если перекрывается

And then you can perform the required actions, for example, destroy a copy of the grenade or reset its motion vector.
Hope it was helpful. If so, please mark my answer as correct. Thanks for reading.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question