Firing bullets from a rotating gun

后端 未结 2 2052
甜味超标
甜味超标 2020-12-04 03:30

My question is connected to this question: rotating gun with restricted movement

What calculations do you need to do to get bullets firing from the gun muzzle?

2条回答
  •  自闭症患者
    2020-12-04 03:48

    I achieved what I needed to do with thefollowing code which is the same as above with a very slight modification which is explained in the code. @skrx answer and the comment by Nick A. aided me to achieve this.

    def gun_radar(self):
    
        for p in self.gameobjects:
    
            if "R" in p.name or "L" in p.name:
    
                if abs(p.rect.centerx - self.hero.rect.centerx) < p.radar and abs(p.rect.centery - self.hero.rect.centery) < p.radar:  # if hero within radar
    
                    p.vec_to_target = pygame.math.Vector2(self.hero.rect.center) - p.rect.center
                    p.direction = p.orig_direction.rotate(p.current_angle)
                    p.orientation = p.vec_to_target.dot(p.direction)
    
                    if p.orientation > 2:
                        p.current_angle += 1
                    elif p.orientation < -2:
                        p.current_angle -= 1
    
                    p.current_angle = p.clamp(p.current_angle, p.clamp_min, p.clamp_max)
    
                    p.gun_rotate(-p.current_angle)
    
                    p.timer -= 1  #count down the timer. when zero calculate vector and add bullet to fired_blts
    
                    if p.timer<= 0:
    
                        w, h = p.rect.center
    
                        # adjust for the distance fromm the gun center to the gun muzzle
    
                        w = w + math.cos(math.radians(p.current_angle)) * 28
                        h = h + math.sin(math.radians(p.current_angle)) * 28
                        bullet = Bombullet(bulletimage, w, h)  # create the bullet
    
                        # calculate the velocity
    
                        bullet.xvel = bullet.speed * math.cos(math.radians(p.current_angle))
                        bullet.yvel = bullet.speed * math.sin(math.radians(p.current_angle))
    
                        self.fired_blts.add(bullet)
    
                        p.timer = 100
    

提交回复
热议问题