Collision detection on the y-axis does not work (pygame)

2024/11/14 11:27:56

I am trying to get the collision detection in my code to work. I am using vectors and I want the player sprite to collide and stop when it collides with a sprite group called walls. The problem is that the player can pass through the bottom wall.

I've turned the gravity off in this example.

The x collision is okay but it draws a bit funny, only the y direction won't work properly with the same code.

I've already tried to debug the code with a debugger to no avail.

I'm mainly interested in figuring out why the vertical collision detection doesn't work, but I'd also appreciate suggestions about the horizontal collision detection.

LINKS: Github : Complete code

Current collision detection code:

def collide_with_walls(self, dir):if dir == 'x':hits = pg.sprite.spritecollide(self, self.game.walls, False)if hits:if self.pos.x > 0:self.pos.x = hits[0].rect.left - self.rect.widthif self.pos.x < 0:self.pos.x = hits[0].rect.rightself.rect.x = self.pos.xif dir == 'y':hits = pg.sprite.spritecollide(self, self.game.walls, False)if hits:if self.pos.y >= 0:self.pos.y = Wall.rect.top - self.rect.height / 2if self.pos.y < 0:self.pos.y = hits[0].rect.bottomself.rect.y = self.pos.y
Answer

As far as I can see your horizontal movement and collision detection work correctly. I enabled the vertical movement again and had to fix only a few things. Wall had to be changed to hits[0] and the y-velocity had to be set to 0 after touching a wall.

def collide_with_walls(self, dir):if dir == 'x':hits = pg.sprite.spritecollide(self, self.game.walls, False)if hits:if self.pos.x > 0:self.pos.x = hits[0].rect.left - self.rect.widthif self.pos.x < 0:self.pos.x = hits[0].rect.rightself.rect.x = self.pos.xif dir == 'y':hits = pg.sprite.spritecollide(self, self.game.walls, False)if hits:if self.pos.y >= 0:# `Wall` had to be changed to `hits[0]`.self.pos.y = hits[0].rect.top - self.rect.heightif self.pos.y < 0:self.pos.y = hits[0].rect.bottomself.rect.y = self.pos.yself.vel.y = 0  # Stop the player, otherwise he'll keep accelerating.

There's still a problem: If the player sprite falls too long, it will accelerate and move so fast downwards that it can skip the collision detection with the wall and will just fall through it. Make sure that the sprite can't skip the collision detection, either by limiting the distances that it can fall, giving it a maximum speed or simply by making the walls thicker. You could also use ray casting, but that would be a bit more complex to implement.

https://en.xdnf.cn/q/120499.html

Related Q&A

Search for string within files of a directory

I need help writing a light weight Python (v3.6.4) script to search for a single keyword within a directory of files and folders. Currently, I am using Notepad++ to search the directory of files, altho…

Extract parent and child node from python tree

I am using nltks Tree data structure.Below is the sample nltk.Tree.(S(S(ADVP (RB recently))(NP (NN someone))(VP(VBD mentioned)(NP (DT the) (NN word) (NN malaria))(PP (TO to) (NP (PRP me)))))(, ,)(CC an…

Click button with selenium and python

Im trying to do web scraping with python on and Im having trouble clicking buttons. Ive tried 3 different youtube videos using Xpath, driver.find_element_by_link_text, and driver.find_element. What am …

Combinations of DataFrames from list

I have this:dfs_in_list = [df1, df2, df3, df4, df5]I want to concatenate all combinations of them one after the other (in a loop), like:pd.concat([df1, df2], axis=1) pd.concat([df1, df3], axis=1) p…

Python: iterate through dictionary and create list with results

I would like to iterate through a dictionary in Python in the form of:dictionary = {company: {0: apple,1: berry,2: pear},country: {0:GB,1:US,2:US} }To grab for example: every [company, country] if coun…

Jira Python: Syntax error appears when trying to print

from jira.client import jiraoptions = {server: https://URL.com} jira = JIRA(options, basic_auth=(username, password))issues = jira.search_issues(jqlquery) for issue in issues:print issueI want to print…

Matplotlib plt.xlim([x_min,x_max]), list object not callable

I want to plot a scatterplot, but set the x-label limits.axScatter = plt.subplot(111) axScatter.scatter(x=mean_var_r["Variance"],y=mean_var_r["Mean"]) xlim = [-0.003, 0.003] plt.xli…

Map column birthdates in python pandas df to astrology signs

I have a dataframe with a column that includes individuals birthdays. I would like to map that column to the individuals astrology sign using code I found (below). I am having trouble writing the code …

How to use python pandas to find a specific string in various rows

I am trying to do my taxes. I have over 2,000 rows of data in a CSV of orders. I am trying to just count and print the rows that contain "CA" so I know the ones I need to pay sales tax on. I …

How to cast a list to a dictionary

I have a list as a input made from tuples where the origin is the 1st object and the neighbour is the 2nd object of the tuple. for example :inp : lst = [(a,b),(b,a),(c,),(a,c)] out : {a: (a, [b, c]), …