Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
152 views
in Technique[技术] by (71.8m points)

python - How do I make a sprite "stand' on another sprite in pygame?

I've got two sprites that can detect collisions, but I'm not sure how I can make my character sprite "stand" on my platform. Nothing I've done seems to work.

question from:https://stackoverflow.com/questions/66051754/pygame-how-to-move-an-object-down-and-print-another-directly-above-this-indefi

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you have 2 pygame.Rect objects, you can move the 2nd rectangle on the 1st rectangle by setting the bottom of the 2nd rectangle with the top of the 1st rectangle. With the virtual attributes of pygame.Rect it is easy to do so:

rect2.bottom = rect1.top

Or if you have 2 pygame.sprite.Sprite objects:

sprite2.rect.bottom = sprote1.rect.top

If you have 2 pygame.Surface objects (surf1 and surf2) and the 2 corresponding positions (x1, y1) and (x2, y2), use get_rect() to create pygame.Rect objects from the Surfaces. Move the 2nd rectangle on the 1st rectangle and update the position of the 2nd rectangle:

rect1 = surf1.get_rect(topleft = (x1, y1))
rect2 = surf2.get_rect(topleft = (x2, y2))

rect2.bottom = rect1.top
y2 = rect2.y

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...