algorithm – Recycling bullets versus spawning them on demand

Until now, I know 2 bullets’ algorithms/configurations : (I mean 2 ways of logically creating a bullet class)

  1. Make a bullet class and create only one instance from it that represents the bullet.
    The bullet hides under the player’s image until he shoots it. Then, he won’t be able to shoot again before it reaches the end of the screen and then hides again under the player’s sprite.
    (This configuration uses only one bullet instance for every bullet type, it means that the player cannot shoot multiple bullets of the same type at once)

  2. Make a bullet class and repeatedly create new instances of it as much as the player needs and as long as he can shoot. (depending on the firerate)

Personally, I like the second algorithm, however, I think that creating many instances does slow the performance especially when the number of these instances becomes bigger and bigger (especially at an advanced stage of the game).

So I have some questions in this topic:

  1. Will using numpy arrays instead of lists (in order to store the instances) decrease the risk of slowing the game performance ?

  2. Will deleting some instances regularly prevent from losing the performance ?

pseudocode for this :

if len(bullets_list) >= 5:
    del bullets_list(:4)

Btw I want to know what happens exactly (technically) when an instance is deleted from a list in Python/Pygame.
And if there is already an answer for this, just attach it with your answer 😉

  1. Are there any other algorithms to develop a bullet class ?

  2. Are there any improvements to the previous algorithms in order to have a good & stable performance and to ensure a good UX ?

  3. Finally, how can I choose which configuration/algorithm to use depending on my game ?
    (What are the standards to follow to determine the answer to this question)

dnd 5e – Do players using Renaissance firearms need to keep track of gunpowder as well as bullets, and if so, how many shots is a horn of gunpowder good for?

No, they just need to track bullets.

lets look at the description of firearm ammunition in the DMG, “renaissance and modern firearms use bullets” no mention of powder is given, and as has been stated many times there are no hidden rules.

This is not unrealistic either, often bullets were packed together with the correct measure of powder all wrapped in paper that also acted as wadding to keep the bullet in place. this was the norm from the Napoleonic war to until metal cartridges replaced paper cartridges. So we can assume the powder is included in the “bullet”

enter image description here

shadowrun – Tracking Ammunition consistently in a Hell made of Bullets

Ranged weapons are a mainstay in many games. Most fantasy games come with arrows, bolts, and sling stones. Wild West comes with lead, powder, and percussion caps in the early times and metal cartridges in the later end of the timeframe. Modern games blow out ammunition in the dozens – even hundreds at times.

However, all those expendable items come at bookkeeping troubles: Is there still an arrow in the quiver, is the next chamber a bang or click, or can the MG put out another burst?

In computer games and playing traditional games online, this problem can be mitigated by having some kind of ammo counter on the screen for each weapon user. But table-play doesn’t offer that ease of use. Players have not unlimited floating numbers next to the head or self-updating character sheets.

At a table, the problem however is you need to update manually. In a fantasy game, my elven archer ended up needing a new sheet after the second or third session because I had erased a hole into the spot where ammo was counted. Putting the arrows on a separate sticky note made that page replaceable, but it was prone to be lost. Looking for the main copy of the inventory to make a new one was a noisy thing between the different pages of the sheet – amplified by the limited space on the table – barely more than the open pages of the core book was available to put down stuff for each player to handle the large map in the center.

But fantasy games like that usually don’t need to account for more than 20 or such arrows per player. So were absolutely needed, I had used an ammo-counter D20 for my quiver and used a holder-ring with some sticky in it to make sure it didn’t roll and wouldn’t be accidentally taken as a dice.

Tracking Ammo for the Bullet-Hell

The real problem however is when games combine many people shooting with shooting a lot and variable ammo usage. That is when shooting isn’t happening consistently. This gets us to Shadowrun: Firearms can let loose between one and 10 rounds per action of the runner, runners can have between one and four actions and could shoot akimbo. Oh, and each gun has different ammunition capacities…

In a scene that turned into a bullet hell, I was one of 5 runners. While we fought some rather resistant thing and I took a lot of drain, the other four spent several hundred bullets shooting full-auto. I am sure that at least two players lost count of what was left in their guns at some point: One recalculated twice if he had to reload using a calculator and slowing the game down, the other had a tiny post-it note upon which he just added strikes to see if he still owned any bullets and guesstimated if he had to reload or not.

How could players track the ammunition for their runners in a way that the amount of ammo left in the gun is easy to spot at a distance, fast to update, non-destructive to the character sheet, and not bound to a movable object (dice, marker) that might be accidentally shifted?

unity – Why the bullets are being spawned from the middle of the scene?

I’m making a 2D game with Unity. I have a patrol enemy that has to shoot bullets. The problem is that the bullets are being spawned from a random point at the middle of the scene, instead of bulletSpawnPos (an empty game object which is a child of the pistol). I also want the enemy to shoot whenever the player is near. But it seems like all the code does is to shoot towards it, no matter if it’s near or not. In general I want to solve these two problems that are pretty much related to each other:

  1. Bullets should be spawn frombulletSpawnPos.
  2. Enemy should start shooting whenever the player is near (maybe by triggering something).

Pistol script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Pistol : MonoBehaviour
{
    (SerializeField) GameObject bullet;
    (SerializeField) Transform bulletSpawnPos;
    private bool IsShooting;

   (SerializeField) private float shootDelay = .5f;
    private Enemy enemy;

    void Start()
    {
        enemy = GetComponent<Enemy>();
        InvokeRepeating("Shoot", 2f, shootDelay);
        Rigidbody2D rb = GetComponent<Rigidbody2D>();
    }

    void Shoot()
    {
        GameObject b = Instantiate(bullet);
        b.GetComponent<Bullet>().StartShoot(enemy.IsFacingLeft());
        b.transform.position = bulletSpawnPos.transform.position;
    }
}

Bullet script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Bullet : MonoBehaviour
{
    (SerializeField) float speed;
    (SerializeField) int damage;
    (SerializeField) GameObject bullet;
    GameObject Enemy;
    float timeToDestroy = 3;
    
     NewPlayer target;
    Vector2 moveDirection;

    void Start()
    {
        Rigidbody2D rb = GetComponent<Rigidbody2D>();
        target = GameObject.FindObjectOfType<NewPlayer>();
        moveDirection = (target.transform.position - transform.position).normalized * speed;
        rb.velocity = new Vector2(moveDirection.x, moveDirection.y);
        Destroy(gameObject, 3f);
    }

    public void StartShoot(bool isFacingLeft)
    {
        Rigidbody2D rb = GetComponent<Rigidbody2D>();
        if (isFacingLeft)
        {
            rb.velocity = new Vector2(-speed, 0);
        }
        else
        {
            rb.velocity = new Vector2(speed, 0);
        }

        Destroy(gameObject, timeToDestroy);
    }

    private void OnTriggerEnter2D(Collider2D collision)
     {
         if (collision.gameObject.name.Equals ("Player"))
         {
             Destroy(gameObject);
         }
     } 
}

Enemy script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Enemy : PhysicsObject
{
    (Header("Attributes"))
    (SerializeField) private int attackPower = 10;
    private int direction = 1;
    public int health = 100;
    private int maxHealth = 100;
    (SerializeField) private float maxSpeed;
    (SerializeField) private LayerMask rayCastLayerMask; //Which layer do we want the raycast to interact with?
    (SerializeField) private Vector2 rayCastOffset; //Offset from the center of the raycast origin
    (SerializeField) private float rayCastLength = 2;
    bool isFacingLeft;
    public bool IsFacingLeft()
    {
        return isFacingLeft;
    }

    (Header("References"))
    private RaycastHit2D rightLedgeRaycastHit;
    private RaycastHit2D leftLedgeRaycastHit;
    private RaycastHit2D rightWallRaycastHit;
    private RaycastHit2D leftWallRaycastHit;

    // Update is called once per frame
    void Update()
    {
        targetVelocity = new Vector2(maxSpeed * direction, 0);

        if (targetVelocity.x < -.01)
        {
            transform.localScale = new Vector2(-1, 1);
            isFacingLeft = true;
        }
        else if (targetVelocity.x > .01)
        {
            transform.localScale = new Vector2(1, 1);
            isFacingLeft = false;
        }

        //Check for right ledge!
        rightLedgeRaycastHit = Physics2D.Raycast(new Vector2(transform.position.x + rayCastOffset.x, transform.position.y + rayCastOffset.y), Vector2.down, rayCastLength);
        Debug.DrawRay(new Vector2(transform.position.x + rayCastOffset.x, transform.position.y + rayCastOffset.y), Vector2.down * rayCastLength, Color.blue);
        if (rightLedgeRaycastHit.collider == null) direction = -1;

        //Check for left ledge!
        leftLedgeRaycastHit = Physics2D.Raycast(new Vector2(transform.position.x - rayCastOffset.x, transform.position.y + rayCastOffset.y), Vector2.down, rayCastLength);
        Debug.DrawRay(new Vector2(transform.position.x - rayCastOffset.x, transform.position.y + rayCastOffset.y), Vector2.down * rayCastLength, Color.green);
        if (leftLedgeRaycastHit.collider == null) direction = 1;

        //Check for right wall!
        rightWallRaycastHit = Physics2D.Raycast(new Vector2(transform.position.x, transform.position.y), Vector2.right, rayCastLength, rayCastLayerMask);
        Debug.DrawRay(new Vector2(transform.position.x, transform.position.y), Vector2.right * rayCastLength, Color.red);
        if (rightWallRaycastHit.collider != null) direction = -1;

        //Check for left wall!
        leftWallRaycastHit = Physics2D.Raycast(new Vector2(transform.position.x, transform.position.y), Vector2.left, rayCastLength, rayCastLayerMask);
        Debug.DrawRay(new Vector2(transform.position.x, transform.position.y), Vector2.left * rayCastLength, Color.magenta);
        if (leftWallRaycastHit.collider != null) direction = 1;

        //If health < 0, destroy me
        if (health <= 0)
        {
            Destroy(gameObject);
        }
    }


    //If I collide with the player, hurt the player (health is going to decrease, update the UI)
    void OnCollisionEnter2D(Collision2D col)
    {
        if (col.gameObject == NewPlayer.Instance.gameObject)
        {
            //Hurt the player, then update the UI!
            NewPlayer.Instance.health -= attackPower;
            NewPlayer.Instance.UpdateUI();
        }
    }
}

This is the pistol inspector window.

Bullets Stop when Shooting Unity 2D

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Makarov : MonoBehaviour
{
    public GameObject Bullet;

    public float BulletSpeed;

    public Transform ShootPoint;

    // Update is called once per frame
    void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            shoot();
        }
    }

    void shoot()
    {
        GameObject BulletIns = Instantiate(Bullet, ShootPoint.position, ShootPoint.rotation);
        BulletIns.GetComponent<Rigidbody2D>().AddForce(BulletIns.transform.forward * BulletSpeed);
    }
}

When I shoot the bullets just stop right in front if the gun.
This is for a top down shooting.

How to make my sprite shoot fireballs (bullets) in pygame?

This is my Sprite1.py program which I import to my main.py program. It contains all the classes I use in my main.py. I tried to create bullets based on a program I saw online but it doesn’t work for me. Could anyone help me figure out how to successfully make it work? I don’t know how to add the Bullet class from my Sprite.py program to the main.py one.

import pygame
import sys
import os
import time
import random
from pygame import mixer
from pygame.locals import *

def showStartScreen(surface):
    show = True
    while show == True:
        startbg = pygame.image.load(os.path.join('images', 'Starting_scr.png'))
        surface.blit(startbg, (0,0))
        pygame.display.flip()
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                show = False

pygame.init()

class Player(pygame.sprite.Sprite):
    '''
    Spawn a player
    '''
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        super().__init__()
        self.movex = 0
        self.movey = 0
        self.frame = 0
        self.images = ()
        self.imagesleft = ()
        self.imagesright = ()
        self.alpha = (0,0,0)
        self.ani = 4 # animation cycles
        for i in range(1,5):
            img = pygame.image.load(os.path.join('images','hero' + str(i) + '.png')).convert()
            img.convert_alpha()
            img.set_colorkey(self.alpha)
            self.imagesright.append(img)
            self.image = self.imagesright(0)
            self.rect  = self.image.get_rect()
            #self.rect = self.image.get_rect(center=pos)
            self.all_sprites = all_sprites
            self.add(self.all_sprites)
            self.bullets = bullets
            self.bullet_timer = .1
        for i in range(1,5):
            img = pygame.image.load(os.path.join('images','hero' + str(i) + '.png')).convert()
            img = pygame.transform.flip(img, True, False)
            img.convert_alpha()
            img.set_colorkey(self.alpha)
            self.imagesleft.append(img)
            self.image = self.imagesleft(0)
            self.rect  = self.image.get_rect()
            #self.rect = self.image.get_rect(center=pos)
            self.all_sprites = all_sprites
            self.add(self.all_sprites)
            self.bullets = bullets
            self.bullet_timer = .1

    def control(self,x,y):
        '''
        control player movement
        '''
        self.movex += x
        self.movey -= y
        self.bullets

    def update(self, dt):
        '''
        Update sprite position
        '''
        self.rect.center = pg.mouse.get_pos()
        self.rect.x = self.rect.x + self.movex
        self.rect.y = self.rect.y + self.movey

        # moving left
        if self.movex < 0:
            self.frame += 1
            if self.frame > 3*self.ani:
                self.frame = 0
            self.image = self.imagesleft(self.frame//self.ani)

        # moving right
        if self.movex > 0:
            self.frame += 1
            if self.frame > 3*self.ani:
                self.frame = 0
            self.image = self.imagesright(self.frame//self.ani)

        mouse_pressed = pg.mouse.get_pressed()
        self.bullet_timer -= dt  # Subtract the time since the last tick.
        if self.bullet_timer <= 0:
            self.bullet_timer = 0  # Bullet ready.
            if mouse_pressed(0):  # Left mouse button.
                # Create a new bullet instance and add it to the groups.
                Bullet(pygame.mouse.get_pos(), self.all_sprites, self.bullets)
                self.bullet_timer = .1  # Reset the timer.


class Bullet(pygame.sprite.Sprite):

    def __init__(self, pos, *sprite_groups):
        super().__init__(*sprite_groups)
        BULLET_IMG = pygame.image.load(os.path.join('images','fireball.png')).convert_alpha()
        self.image = BULLET_IMG
        self.rect = self.image.get_rect(center=pos)
        self.pos = pygame.math.Vector2(pos)
        self.vel = pygame.math.Vector2(0, -450)
        self.damage = 10

    def update(self, dt):
        # Add the velocity to the position vector to move the sprite.
        self.pos += self.vel * dt
        self.rect.center = self.pos  # Update the rect pos.
        if self.rect.bottom <= 0:
            self.kill()

This is my main.py program


import pygame
import os
import time
from pygame import mixer
from pygame.locals import *
import Sprite1


width = 960
height = 720

fps = 40        # frame rate
#ani = 4        # animation cycles
clock = pygame.time.Clock()
pygame.init()
main = True

pygame.init()
FPSCLOCK = pygame.time.Clock()
DISLAYSURF = pygame.display.set_mode((width,height))

surface = pygame.display.set_mode((width,height))
pygame.display.set_caption('B.S.G.!!!')
background = pygame.image.load(os.path.join('images','Bg.png')).convert()
backdropbox = surface.get_rect()
pygame.mixer.music.load('.\sounds\Fairy.mp3')
pygame.mixer.music.play(-1, 0.0)


player = Sprite1.Player()   # spawn player
fire = Sprite1.Bullet()
player.rect.x = 50
player.rect.y = 500
player_list = pygame.sprite.Group()
player_list.add(player)
steps = 10      # how fast to move

Sprite.showStartScreen(surface)

while main == True:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit(); sys.exit()
            main = False
        #if event.type == pygame.MOUSEBUTTONDOWN:

            #if Bullet.bullet_timer <= 0:
                #Bullet.bullet_timer = 0  # Bullet ready.
                #if mouse_pressed(0):  # Left mouse button.
                    ## Create a new bullet instance and add it to the groups.
                    #Bullet(pg.mouse.get_pos(), self.all_sprites, self.bullets)
                    #Bullet.bullet_timer = .1  # Reset the timer.

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                player.control(-steps,0)
            if event.key == pygame.K_RIGHT:
                player.control(steps,0)
            if event.key == pygame.K_UP:
                player.rect.y -= 100

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT:
                player.control(steps,0)
            if event.key == pygame.K_RIGHT:
                player.control(-steps,0)
            if event.key == pygame.K_UP:
                player.rect.y += 100
            if event.key == ord('q'):
                pygame.quit()
                sys.exit()
                main = False

    surface.blit(background, (0, 0))
    player.update()
    player_list.draw(surface) #refresh player position
    pygame.display.flip()
    clock.tick(fps)
```

python – Problem With Enemy Bullets Attacking The Player Pygame

I am trying to make my enemy bullets attack the player but it only attack its x and y how could I make it curve instead of zigzagging VIDEO the bullets only attack the y axis and it wont curve or go to the player only attacks 2 positions

this goes on my main loop and appends projectiles

         for shootss in shootsright:

                if shootss.x < 500 and shootss.x > 0:

                    if enemyshoots1.x < playerman.x:

                        shootss.x +=  5
                    else:
                        shootss.x -= 5
                else:
                    shootsright.pop(shootsright.index(shootss))
                if shootss.y < 500 and shootss.y >0:
                    if enemyshoots1.y < playerman.y:
                        shootss.y += 5
                    else:
                        shootss.y -= 5
                else:
                    shootsright.pop(shootsright.index(shootss))


            if len(shootsright) < 2:
                    shootsright.append(Bools(round(enemyshoots1.x+enemyshoots1.width-107),round(enemyshoots1.y + enemyshoots1.height-50),(0,0,0)))
                # projectile class for each of the bullets

my enemy bullets class

    # enemys bullets
    ksud = pygame.image.load("heart.png")
    class Bools(object):
       def __init__(self, x, y,color):
           self.x = x
           self.y = y
           self.ksud = pygame.image.load("heart.png")
           self.hitbox  = self.ksud.get_rect()
           self.rect  = self.ksud.get_rect()
           self.rect.topleft = (self.x,self.y)
           self.speed = 10
           self.color = color
           self.hitbox = (self.x + 57, self.y + 33, 29, 52) # NEW
       def draw(self, window):
            self.rect.topleft = (self.x,self.y)
            player_rect = self.ksud.get_rect(center = self.rect.center) 
            player_rect.centerx += 0 # 10 is just an example
            player_rect.centery += 0 # 15 is just an example
            window.blit(self.ksud, player_rect)
            self.hitbox = (self.x + 97, self.y + 33, 10, 10) # NEW
            window.blit(self.ksud,self.rect)



Who wishes they were a cop tonight so you could throw tear gas and shoot rubber bullets at these rioters?

You’d be too busy arresting the CNN Journalist, shooting a rubber bullet into the eye of journalists causing them to lose their eye, setting the Autozone on fire, attacking the CNN Headquarters, opening car doors of black couples tazing them then slashed their tires before arresting them all for driving down the F’kin road, etc.

Wake-up

Keyboard Shortcuts – AutoHotKey: How do I add special character bullets to a string of letters?

I try to add special characters (different types of points, as seen in the last line).

Special characters in the Windows character table

This works, but I want to use a string

#+d::Send {U+25CF} ; dot solid

I tried – but it does not work

:R*?:dot1::Send {U+25CF} ; dot solid

Does anyone know how to make it work?