En los juegos una parte fundamental y muy importante son las colisiones entre objetos.
En este video vemos como detectar que un rectangulo toca al otro.
En este video vemos como detectar que un rectangulo toca al otro.
nota: el codigo siguiente esta rectificado con respecto al video segun se indica al final del mismo, para verificar que el rectangulo no se salga de los limites de la pantalla.
# -*- coding: utf-8 -*-"""Created on Tue Aug 14 15:44:41 2018
@author: Jose"""
#importamos modulosimport pygame, sysfrom pygame.locals import *from random import randint
#init antes de usar pygamepygame.init()#declaramos ventana con alto anchoventana=pygame.display.set_mode((500,400))#titulopygame.display.set_caption("Colisiones")#variablescolorFondo=(25,150,70)colorRectangulo1=(255,255,255)colorRectangulo2=(255,55,0)velocidad=10
posX,posY=randint(1,400),randint(1,300)#rectangulosrectangulo1=pygame.Rect(5,10,70,40)rectangulo2=pygame.Rect(posX,posY,70,40)#bucle ejecucion ventanawhile True: ventana.fill(colorFondo) #dibujamos rectangulos pygame.draw.rect(ventana,colorRectangulo1,rectangulo1) pygame.draw.rect(ventana,colorRectangulo2,rectangulo2) #codigo seguir puntero raton posX,posY=pygame.mouse.get_pos() #lo centramos a rectangulo posX=posX-35 posY=posY-20 #cambiamos posicion rectangulo 1 rectangulo1.left=posX rectangulo1.top=posY #colision if rectangulo1.colliderect(rectangulo2): print("colisionando") posX,posY=randint(1,400),randint(1,300)
#cambiamos las coordenadas si se sale de limites if posX<0: posX=0 elif posX>430: posX=430 elif posY<0: posY=0 elif posY>360: posY=360 rectangulo2.left=posX-35 rectangulo2.top=posY-20 #control de eventos for evento in pygame.event.get(): if evento.type==QUIT: pygame.quit() sys.exit() #actualizamos segun pulse tecla flechas elif evento.type==pygame.KEYDOWN: if evento.key==K_LEFT: posX-=velocidad if posX<0: posX=0 elif evento.key==K_RIGHT: posX+=velocidad if posX>(500-70): posX=500-70 elif evento.key==K_UP: posY-=velocidad if posY<0: posY=0 elif evento.key==K_DOWN: posY+=velocidad if posY>360: posY=360 #actualiza ventana pygame.display.update()
No hay comentarios:
Publicar un comentario
Se procedera a revision para su pronta publicacion en caso de que no incumpla las normas de blogger.