鱼C论坛

 找回密码
 立即注册
查看: 958|回复: 2

[已解决]碰撞检测

[复制链接]
发表于 2019-1-3 11:39:37 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 小章郎 于 2019-1-3 11:43 编辑

代码如下:
  1. import pygame as pg
  2. import sys
  3. from pygame.locals import *
  4. from random import *

  5. class Ball(pg.sprite.Sprite):
  6.     def __init__(self, gray_ball, color_ball, position, speed, bg_size, target):
  7.         # Call the parent class (Sprite) constructor
  8.         pg.sprite.Sprite.__init__(self)

  9.         self.gray_ball = pg.image.load(gray_ball).convert_alpha()
  10.         self.color_ball = pg.image.load(color_ball).convert_alpha()
  11.         self.rect = self.gray_ball.get_rect()
  12.         # 小球的位置
  13.         self.rect.left, self.rect.top = position
  14.         self.speed = speed
  15.         self.side = [choice([-1, 1]), choice([-1, 1])]
  16.         self.width, self.height = bg_size[0], bg_size[1]
  17.         self.target = target
  18.         self.control = False
  19.         self.collide = False

  20.     def move(self):
  21.         if self.control:
  22.             self.rect = self.rect.move(self.speed)
  23.         else:
  24.             self.rect = self.rect.move([self.side[0] * self.speed[0], \
  25.                                         self.side[1] * self.speed[1]])

  26.         # 类似实现贪吃蛇穿入墙壁从对面墙壁出来(左右方向)
  27.         if self.rect.right < 0:
  28.             self.rect.left = self.width
  29.         elif self.rect.left > self.width:
  30.             self.rect.right = 0

  31.         # (上下方向) 从下往上 和 从上往下
  32.         elif self.rect.bottom < 0:
  33.             self.rect.top = self.height

  34.         elif self.rect.top > self.height:
  35.             self.rect.bottom = 0

  36.     def check(self, motion):
  37.         if self.target < motion < self.target + 5:
  38.             return True
  39.         else:
  40.             return False

  41. class Glass(pg.sprite.Sprite):
  42.     def __init__(self, glass_image, mouse_image, bg_size):
  43.         #初始化动画精灵
  44.         pg.sprite.Sprite.__init__(self)

  45.         self.glass_image = pg.image.load(glass_image).convert()
  46.         self.glass_image.set_alpha(100)
  47.         self.glass_rect = self.glass_image.get_rect()
  48.         self.glass_rect.left, self.glass_rect.top = \
  49.             (bg_size[0] - self.glass_rect.width) // 2, \
  50.             bg_size[1] - self.glass_rect.height

  51.         self.mouse_image = pg.image.load(mouse_image).convert_alpha()
  52.         self.mouse_rect = self.mouse_image.get_rect()
  53.         self.mouse_rect.left, self.mouse_rect.top = \
  54.             self.glass_rect.left, self.glass_rect.top
  55.         #隐藏鼠标实际位置
  56.         pg.mouse.set_visible(False)

  57. def main():
  58.     pg.init()

  59.     gray_ball = 'gray_ball.png'
  60.     color_ball = 'color_ball.png'
  61.     glass_image = 'glass.jpg'
  62.     bg_image = 'background.png'
  63.     mouse_image = 'hand.png'

  64.     #添加背景音乐
  65.     pg.mixer.music.load('bg_music.ogg')
  66.     pg.mixer.music.play()
  67.     pg.mixer.music.set_volume(0.5)

  68.     #添加音效
  69.     loser_sound = pg.mixer.Sound('loser.wav')
  70.     laugh_sound = pg.mixer.Sound('laugh.wav')
  71.     winner_sound = pg.mixer.Sound('winner.wav')
  72.     hole_sound = pg.mixer.Sound('hole.wav')

  73.     running = True

  74.     #音乐播放完结束游戏,添加用户事件,多个事件,可对USEREVENT进行加一
  75.     GAMEOVER = USEREVENT
  76.     pg.mixer.music.set_endevent(GAMEOVER)

  77.     #根据背景图片指定设置游戏界面尺寸
  78.     bg_size = width, height = 1024, 681
  79.     screen = pg.display.set_mode(bg_size)
  80.     pg.display.set_caption('Play the ball')

  81.     background = pg.image.load(bg_image).convert_alpha()

  82.     hole = [(117, 119, 199, 201), (225, 227, 390, 392), \
  83.             (503, 505, 320, 322), (698, 700, 192, 194), \
  84.             (906, 908, 419, 421)]

  85.     msgs = []
  86.     #用来存放小球的列表
  87.     balls = []
  88.     group = pg.sprite.Group()

  89.     #创建五个小球
  90.     for i in range(5):
  91.         # 球的尺寸是100*100 随机产生小球的位置
  92.         position = randint(0, width - 100), randint(0, height - 100)
  93.         # 两个元素的一个列表,表示x轴和y轴方向的速度
  94.         speed = [randint(1, 10), randint(1, 10)]
  95.         # 实例化小球对象 分别传入Surface对象 位置二元组 速度两元素列表
  96.         ball = Ball(gray_ball, color_ball, position, speed, bg_size, i*(i+1))
  97.         # 碰撞检测之后不从组里面删除
  98.         while pg.sprite.spritecollide(ball, group, False, None):#这个能完美检测碰撞
  99.         #while pg.sprite.spritecollide(ball, group, False, pg.sprite.collide_circle):
  100.             ball.rect.left, ball.rect.top = randint(0, width - 100), \
  101.                                             randint(0, height - 100)

  102.         balls.append(ball)  # 将小球加入到小球列表中
  103.         group.add(ball)
  104.         glass = Glass(glass_image, mouse_image, bg_size)

  105.         #motion变量用于记录鼠标每秒事件数量
  106.         motion = 0

  107.         #设置计时器,计算一秒
  108.         MYTIMER = USEREVENT + 1
  109.         pg.time.set_timer(MYTIMER, 1000)
  110.         #设置重复发送按键事件,按住重复发送,set_rpeat(delay, interval)delay指定第一次发送事件的延迟时间,
  111.         #interval指定重复发事件的时间间隔,如果不带任何参数表示取消重复发送事件
  112.         pg.key.set_repeat(100, 100 )

  113.         clock = pg.time.Clock()

  114.     while running:
  115.         for event in pg.event.get():
  116.             if event.type == QUIT:
  117.                 sys.exit()

  118.             elif event.type == GAMEOVER:
  119.                 loser_sound.play()
  120.                 pg.time.delay(2000)
  121.                 laugh_sound.play()
  122.                 running = False

  123.             elif event.type == MYTIMER:
  124.                 if motion:
  125.                     for each in group:
  126.                         if each.check(motion):
  127.                             each.speed = [0, 0]
  128.                             each.control = True
  129.                     motion = 0

  130.             elif event.type == MOUSEMOTION:
  131.                 motion += 1

  132.             elif event.type == KEYDOWN:
  133.                 if event.key == K_w:
  134.                     for each in group:
  135.                         if each.control:
  136.                             each.speed[1] -= 1

  137.                 if event.key == K_s:
  138.                     for each in group:
  139.                         if each.control:
  140.                             each.speed[1] += 1

  141.                 if event.key == K_a:
  142.                     for each in group:
  143.                         if each.control:
  144.                             each.speed[0] -= 1

  145.                 if event.key == K_d:
  146.                     for each in group:
  147.                         if each.control:
  148.                             each.speed[0] += 1
  149.                
  150.                 #检测是否入洞
  151.                 if event.key == K_SPACE:
  152.                     for each in group:
  153.                         if each.control:
  154.                             for each_hole in hole:
  155.                                 if each_hole[0] <= each.rect.left <= each_hole[1] and \
  156.                                         each_hole[2] <= each.rect.top <= each_hole[3]:
  157.                                     each.speed = [0, 0]
  158.                                     group.remove(each)
  159.                                     temp = balls.pop(balls.index(each))
  160.                                     balls.insert(0, temp)
  161.                                     hole.remove(each_hole)
  162.                                 
  163.                                 #所有的洞填满游戏胜利
  164.                                 if not hole:
  165.                                     pg.mixer.music.stop()
  166.                                     winner_sound.play()
  167.                                     pg.time.delay(3000)
  168.                                     msg = pg.image.load('win.png').convert_alpha()
  169.                                     msg.pos = (width - msg.get_width()) // 2, \
  170.                                               (height - msg.get_height()) // 2

  171.                                     msgs.append((msg, msg.pos))
  172.                                     laugh_sound.play()

  173.         screen.blit(background, (0, 0))
  174.         screen.blit(glass.glass_image, glass.glass_rect)
  175.         #控制鼠标光标不离开玻璃面板
  176.         glass.mouse_rect.left, glass.mouse_rect.top = pg.mouse.get_pos()
  177.         if glass.mouse_rect.left < glass.glass_rect.left:
  178.             glass.mouse_rect.left = glass.glass_rect.left
  179.         if glass.mouse_rect.left > glass.glass_rect.right - glass.mouse_rect.width:
  180.             glass.mouse_rect.left = glass.glass_rect.right - glass.mouse_rect.width
  181.         if glass.mouse_rect.top < glass.glass_rect.top:
  182.             glass.mouse_rect.top = glass.glass_rect.top
  183.         if glass.mouse_rect.bottom > glass.glass_rect.bottom - glass.mouse_rect.height:
  184.             glass.mouse_rect.bottom = glass.glass_rect.bottom - glass.mouse_rect.height

  185.         screen.blit(glass.mouse_image, glass.mouse_rect)


  186.         for each in balls:
  187.             each.move()
  188.             if each.collide:
  189.                 each.speed = [randint(1, 10), randint(1, 10)]
  190.                 each.collide = False

  191.             if each.control:
  192.                 screen.blit(each.color_ball, each.rect)
  193.             else:
  194.                 screen.blit(each.gray_ball, each.rect)

  195.         for each in group:
  196.             #检查与其他是否碰撞需要去掉自身
  197.             group.remove(each)

  198.             if pg.sprite.spritecollide(each, group, False, None):#这个能完美检测碰撞
  199.             #if pg.sprite.spritecollide(each, group, False, pg.sprite.collide_circle):
  200.                 each.side[0] = -each.side[0]
  201.                 each.side[1] = -each.side[1]
  202.                 each.collide = True
  203.                 if each.control:
  204.                     each.side[0] = -1
  205.                     each.side[1] = -1
  206.                     each.control = False
  207.             #检测碰撞后再次添加回去   
  208.             group.add(each)

  209.         for msg in msgs:
  210.             screen.blit(msg[0], msg[1])

  211.         pg.display.flip()
  212.         clock.tick(30)

  213. if __name__ == '__main__':
  214.     main()

复制代码

为了检测碰撞,用了如下代码
pg.sprite.spritecollide(ball, group, False, None)
pg.sprite.spritecollide(each, group, False, None)
上面两段能正常检测碰撞

可是视频里面用的如下两段
pg.sprite.spritecollide(ball, group, False, pg.sprite.collide_circle)
pg.sprite.spritecollide(each, group, False, pg.sprite.collide_circle)
却远远的没碰到就弹开了,我看小甲鱼的视频里不会啊,能完美检测碰撞,就是上面这样写的,是我上面地方写错了吗?

最佳答案
2019-1-3 13:45:43
后边加circle是能完美检测圆形的,默认的是矩形检测不能完美检测碰撞。还有你的素材最好使用小甲鱼的原版
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2019-1-3 13:45:43 | 显示全部楼层    本楼为最佳答案   
后边加circle是能完美检测圆形的,默认的是矩形检测不能完美检测碰撞。还有你的素材最好使用小甲鱼的原版
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-1-3 18:31:45 | 显示全部楼层
python真是博大精深
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-9-9 09:18

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表