How to check which object my character is colliding with?

点点圈 提交于 2019-12-11 12:56:40

问题


I am working on collision detection for a game, so that if the character runs into an object they stop moving. As part of my solution for this, I have made two functions that iterate through a list of on screen objects to check for collision.

The first function (on_key_up) checks for collision when the direction key is held down and then stops character movement when True.

The second part of this is another function (on_key_up) that moves the character slightly out of the collision zone so he is free to move again. This is triggered when releasing the direction key.

The problem is that I need to access the height and width attributes of whichever object the character is colliding with so I was wondering if there is a way to do this.

I posted a snippet of what I did so you can see the direction I'm trying to go in.

What did I do wrong here?

def on_keyboard_up(self, keyboard, keycode):
        if keycode[1] == 'left':
            self.source = 'selectionscreen/faceleft.png'
                for i in listofwidgets:
                    if self.collide_widget(i):
                        self.x = ((listofwidgets(i).x + listofwidgets(i).width + .1)-self.x) + self.x

回答1:


I think you need to simply change:

self.x = ((listofwidgets(i).x + listofwidgets(i).width + .1)-self.x) + self.x

to:

self.x = (i.x + i.width + .1)-self.x) + self.x

Also listofwidgets(i) would be a function call, it should probably be listofwidgets[i] (if it wasn't just a typo)




回答2:


listofwidgets(i) is the object you are colliding with, so either store that widget, or i in a variable for later use.



来源:https://stackoverflow.com/questions/22706207/how-to-check-which-object-my-character-is-colliding-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!