[pygame] detect mouse over a box
O k guys I am learning python and eventually want to make a game, but for now I'm simply sticking with the main menu. I have a box named bar, and it is gray, I want to make it turn black when the mouse is over it, and expand by a few pixels when it is clicked on. I just can't seem to grasp how to detect if the mouse is in the area of the bar. How would I do this?
Thanks for any help,
Joe
If the mouse is colliding with the image, just change the image to draw. All you have to do is check if they are touching, JOE. Google.com or pygame.org will probably have what your looking for, and maybe even the Articles and resources on this site.
What i'm saying is that I don't know how to detect if they are touching or not. I have made it so that it expands and changes color on mouse down, and returns to normal on mouseup, but I can't figure out how to make it do it only when the mouse is over the box.
....just check if they are touching when the mouse isn't down....
EDIT: and you do that with
pygame.mouse.get_pos (http://www.pygame.org/docs/ref/mouse.html). Once you have the location of the mouse, just check to see if it falls in the image's rectangle.
EDIT: and you do that with
pygame.mouse.get_pos (http://www.pygame.org/docs/ref/mouse.html). Once you have the location of the mouse, just check to see if it falls in the image's rectangle.
I know how to get the mouse position, It's just once I get it I'm confused as what to do with it. I've tried this
I've gotten that to work, but is there a better way?
[Edited by - avgprogramingjoe on August 5, 2007 7:41:29 PM]
import pygamepygame.init()screen = pygame.display.set_mode((640,480))pygame.display.set_caption("Hello, world!")background = pygame.Surface(screen.get_size())background = background.convert()background.fill((100,60,25))clock = pygame.time.Clock()keepGoing = Truecolor = (100, 100, 100)size = (150, 50)pos = (50, 50) #Set up main loopwhile keepGoing: #Timer to set frame rate clock.tick(30) touch = pygame.mouse.get_pos() bar = pygame.Surface(size) bar = bar.convert() bar.fill(color) bar.fill(color) for event in pygame.event.get(): if event.type == pygame.QUIT: keepGoing = False if touch[0] >= 50 and touch[0] <= 200 and touch[1] >= 50 and touch[1] <=100: if event.type == pygame.MOUSEBUTTONDOWN: color = (50, 50, 50) size = (160, 60) pos = (45, 45) if event.type == pygame.MOUSEBUTTONUP: color = (100, 100, 100) size = (150, 50) pos = (50, 50) screen.blit(background, (0,0)) screen.blit(bar, pos) pygame.display.flip()
I've gotten that to work, but is there a better way?
[Edited by - avgprogramingjoe on August 5, 2007 7:41:29 PM]
Have a look at the pygame.Rect class, it's incredibly useful. You can do what you want with the collidepoint method.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement