logo
down
shadow

Pygame- make bullet shoot toward cursor direction


Pygame- make bullet shoot toward cursor direction

By : user3042728
Date : November 29 2020, 12:01 PM
around this issue The issue is that you calculate the the direction of the bullet by vector from the current position of the bullet to the target point (bullet.targetX, bullet.targetY).
Once the bullet reaches the target, then this direction is (0, 0) and the bullet doesn't move any more.
code :
bullet.diffX = targetX - bullet.x
bullet.diffY = targetY - bullet.y
ang = math.atan2(bullet.diffY, bullet.diffX)
bullet.x += math.cos(ang)*bullet.vel
bullet.y += math.sin(ang)*bullet.vel
for bullet in bullets:
   if pygame.Rect(0, 0, 1000, 800).collidepoint(bullet.x, bullet.y):
       # [...]
for bullet in bullets:
   radius = 5
   bullet_rect = pygame.Rect(-radius, -radius, radius, radius);
   bullet_rect.center = (bullet.x, bullet.y)
   if pygame.Rect(0, 0, 1000, 800).colliderect(bullet_rect):
       # [...]
bullet.pos = pg.math.Vector2(bullet.x, bullet.y)
bullet.dir = pg.math.Vector2(targetX, targetY) - bullet.pos
bullet.dir = bullet.dir.normalize()
for bullet in bullets:

    if #[...]

        bullet.pos += bullet.dir * bullet.vel
        bullet.x, bullet.y = (round(bullet.pos.x), round(bullet.pos.y))


Share : facebook icon twitter icon
HTML5 - JS: Shoot Bullet From Facing Direction

HTML5 - JS: Shoot Bullet From Facing Direction


By : Richard D.
Date : March 29 2020, 07:55 AM
I wish this help you Actually, I would recommend not using trig functions, simply for efficiency. Math.atan2, Math.cos, and Math.sin can get expensive.
You already have (slightly renamed)
code :
var deltaX = input.mouseX - (this.localX + this.width/2);
var deltaY = input.mouseY - (this.localY + this.height/2);
var magnitude = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
var velocityScale = bulletSpeed / magnitude;
velocityInstance.x = deltaX * velocityScale;
velocityInstance.y = deltaY * velocityScale;
pygame: I am trying to shoot a bullet from my Tank but I can't find the start point of the bullet

pygame: I am trying to shoot a bullet from my Tank but I can't find the start point of the bullet


By : kimig82
Date : March 29 2020, 07:55 AM
Any of those help part of the Tanks class: , You need something like this
code :
a = RealTank.Trect.centerx + math.cos(math.radians(RealTank.turret_angle+90))*55
b = RealTank.Trect.centery + math.sin(math.radians(RealTank.turret_angle-90))*55

pygame.draw.circle(screen,red,[int(a), int(b)],5,0)
How to shoot a bullet at an angle in pygame?

How to shoot a bullet at an angle in pygame?


By : user1745632
Date : March 29 2020, 07:55 AM
this one helps. You should normalize the distance to the mouse if you want the speed not to depend on the mouse distance.
In other words, regardless of where the mouse is, use the coordinates of the point which is in that same direction, but at a fixed distance from the starting position, e.g. when you calculate your b_m_xand b_m_y, do this:
code :
b_m_x, b_m_y = m_x - self.pos.x, m_y - self.pos.y

distance = (b_m_x ** 2 + b_m_y ** 2) ** .5

if distance != 0:
    # if distance is 0, nothing can be done

    NORMALIZED_DISTANCE = 100
    mutiplier = NORMALIZED_DISTANCE / distance

    b_m_x *= multipler
    b_m_y *= multipler
How to shoot bullets from a character facing in direction of cursor in pygame?

How to shoot bullets from a character facing in direction of cursor in pygame?


By : Div1000
Date : March 29 2020, 07:55 AM
this will help Pass the mouse position to rotator.shoot(), when the mouse button is pressed:
code :
if event.type == pg.MOUSEBUTTONDOWN:
    rotator.shoot(event.pos)
def shoot(self, mousepos):
    dx = mousepos[0] - self.rect.centerx
    dy = mousepos[1] - self.rect.centery
    if abs(dx) > 0 or abs(dy) > 0:
        bullet = Bullet(self.rect.centerx, self.rect.centery, dx, dy)
        all_sprites.add(bullet)
        bullets.add(bullet)
class Bullet(pg.sprite.Sprite):
    def __init__(self, x, y, dx, dy):
        pg.sprite.Sprite.__init__(self)
        self.image = pg.transform.smoothscale(pg.image.load('bullet.png').convert_alpha(), (10,10))
        self.rect = self.image.get_rect()
        self.rect.center = (x, y)
        self.speed = 8
        self.pos = pg.math.Vector2(x, y)
        self.dir = pg.math.Vector2(dx, dy).normalize()
class Bullet(pg.sprite.Sprite):

    # [...]

     def update(self):

        self.pos += self.dir * self.speed
        self.rect.center = (round(self.pos.x), round(self.pos.y))

        if not self.rect.colliderect(0, 0, width, height):
            self.kill()

Python Pygame press two direction key and another key to shoot there's no bullet

Python Pygame press two direction key and another key to shoot there's no bullet


By : user3428213
Date : March 29 2020, 07:55 AM
I hope this helps you . If you press UP + LEFT + SPACE then the SPACE key doesn't appear to be pressed immediately. You've to release the UP or LEFT key to get the pygame.KEYDOWN event for SPACE.
This is a known bug in pygame and doesn't seem to be solved yet: Incorrect handling of pressed keys #235
Related Posts Related Posts :
  • Tuning the hyperparameter with gridsearch results in overfitting
  • some coordinates that I extracted from geocoder in Python are not saving in the variable I created
  • 7C in cs circles- python Im not sure what is wrong with this yet
  • How to fix 'AttributeError: 'list' object has no attribute 'shape'' error in python with Tensorflow / Keras when loading
  • python - thread`s target is a method of an object
  • Retrieve Variable From Class
  • What is the reason for matplotlib for printing labels multiple times?
  • Why would people use ThreadPoolExecutor instead of direct function call?
  • When clear_widgets is called, it doesnt remove screens in ScreenManager
  • Python can't import function
  • Pieces doesn't stack after one loop on my connect4
  • How to change font size of all .docx document with python-docx
  • How to store a word with # in .cfg file
  • How to append dictionaries to a dictionary?
  • How can I scrape text within paragraph tag with some other tags then within the paragraph text?
  • Custom entity ruler with SpaCy did not return a match
  • Logging with two handlers - one to file and one to stderr
  • How to do pivot_table in dask with aggfunc 'min'?
  • This for loop displays only the last entry of the student record
  • How to split a string by a specific pattern in number of characters?
  • Python 3: how to scrape research results from a website using CSFR?
  • Setting the scoring parameter of RandomizedSeachCV to r2
  • How to send alert or message from view.py to template?
  • How to add qml ScatterSeries to existing qml defined ChartView?
  • Django + tox: Apps aren't loaded yet
  • My css and images arent showing in django
  • Probability mass function sum 2 dice roll?
  • Cannot call ubuntu 'ulimit' from python subprocess without using shell option
  • Dataframe Timestamp Filter for new/repeating value
  • Problem with clicking select2 dropdownlist in selenium
  • pandas dataframe masks to write values into new column
  • How to click on item in navigation bar on top of page using selenium python?
  • Add multiple EntityRuler with spaCy (ValueError: 'entity_ruler' already exists in pipeline)
  • error when replacing missing ')' using negative look ahead regex in python
  • Is there a way to remove specific strings from indexes using a for loop?
  • select multiple tags by position in beautifulSoup
  • pytest: getting AttributeError: 'CaptureFixture' object has no attribute 'readouterror' capturing stdout
  • Shipping PyGObject/GTK+ app on Windows with MingW
  • Python script to deduplicate lines in multiple files
  • How to prevent window and widgets in a pyqt5 application from changing size when the visibility of one widget is altered
  • How to draw stacked bar plot from df.groupby('feature')['label'].value_counts()
  • Python subprocess doesn't work without sleep
  • How can I adjust 'the time' in python with module Re
  • Join original np array with resulting np array in a form of dictionary? multidimensional array? etc?
  • Forcing labels on histograms in each individual graph in a figure
  • For an infinite dataset, is the data used in each epoch the same?
  • Is there a more efficent way to extend a string?
  • Is it possible to do this loop in a one-liner?
  • invalid literal for int() with base 10: - django
  • Why does my code print a value that I have not assigned as yet?
  • the collatz func in automate boring stuff with python
  • How to find all possible combinations of parameters and funtions
  • about backpropagation deep neural network in tensorflow
  • Sort strings in pandas
  • How do access my flask app hosted in docker?
  • Replace the sentence include some text with Python regex
  • Counting the most common element in a 2D List in Python
  • logout a user from the system using a function in python
  • mp4 metadata not found but exists
  • Django: QuerySet with ExpressionWrapper
  • shadow
    Privacy Policy - Terms - Contact Us © festivalmusicasacra.org