How to shoot a bullet towards the mouse cursor in PyGame?
You're encountering issues in making your bullet shoot towards the mouse cursor in PyGame. Your code currently involves creating a Bullet class, adding bullets, and calculating the angle. However, you're finding that the bullets are not rotating and moving as expected. Let's go over the approach and improve it.
Firstly, the issue with rotation stems from the fact that pygame.transform.rotate creates a new rotated surface without updating your existing bullet object. To rotate a sprite in place, you need to use sprite.image = pygame.transform.rotate(sprite.image, angle).
As for getting the direction, you're using a constantly changing angle between the player and the mouse position, which results in inconsistent bullet movement. Instead, the direction needs to be set once when the bullet is fired:
self.dir = pygame.mouse.get_rel() # Relative movement since the last event
To normalize the direction and set the speed, you can do this:
dist = math.sqrt(self.dir[0]**2 + self.dir[1]**2) self.speed = self.speed / dist self.dir = (self.dir[0]/dist, self.dir[1]/dist)
Finally, you need to add the calculated speed to the bullet's position in the update function:
self.pos += self.speed[0], self.speed[1]
Here's an example that incorporates the mentioned improvements:
class Bullet(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((10, 10)) self.image.fill((255, 0, 0)) self.rect = self.image.get_rect() self.speed = 10 def update(self): angle = math.atan2(self.dir[1], self.dir[0]) self.image = pygame.transform.rotate(self.image, -angle * (180 / math.pi)) self.pos += self.speed[0], self.speed[1] self.rect = self.image.get_rect(center=self.pos)
The above is the detailed content of How to Make Bullets Shoot Towards the Mouse Cursor in PyGame?. For more information, please follow other related articles on the PHP Chinese website!

Pythonusesahybridmodelofcompilationandinterpretation:1)ThePythoninterpretercompilessourcecodeintoplatform-independentbytecode.2)ThePythonVirtualMachine(PVM)thenexecutesthisbytecode,balancingeaseofusewithperformance.

Pythonisbothinterpretedandcompiled.1)It'scompiledtobytecodeforportabilityacrossplatforms.2)Thebytecodeistheninterpreted,allowingfordynamictypingandrapiddevelopment,thoughitmaybeslowerthanfullycompiledlanguages.

Forloopsareidealwhenyouknowthenumberofiterationsinadvance,whilewhileloopsarebetterforsituationswhereyouneedtoloopuntilaconditionismet.Forloopsaremoreefficientandreadable,suitableforiteratingoversequences,whereaswhileloopsoffermorecontrolandareusefulf

Forloopsareusedwhenthenumberofiterationsisknowninadvance,whilewhileloopsareusedwhentheiterationsdependonacondition.1)Forloopsareidealforiteratingoversequenceslikelistsorarrays.2)Whileloopsaresuitableforscenarioswheretheloopcontinuesuntilaspecificcond

Pythonisnotpurelyinterpreted;itusesahybridapproachofbytecodecompilationandruntimeinterpretation.1)Pythoncompilessourcecodeintobytecode,whichisthenexecutedbythePythonVirtualMachine(PVM).2)Thisprocessallowsforrapiddevelopmentbutcanimpactperformance,req

ToconcatenatelistsinPythonwiththesameelements,use:1)the operatortokeepduplicates,2)asettoremoveduplicates,or3)listcomprehensionforcontroloverduplicates,eachmethodhasdifferentperformanceandorderimplications.

Pythonisaninterpretedlanguage,offeringeaseofuseandflexibilitybutfacingperformancelimitationsincriticalapplications.1)InterpretedlanguageslikePythonexecuteline-by-line,allowingimmediatefeedbackandrapidprototyping.2)CompiledlanguageslikeC/C transformt

Useforloopswhenthenumberofiterationsisknowninadvance,andwhileloopswheniterationsdependonacondition.1)Forloopsareidealforsequenceslikelistsorranges.2)Whileloopssuitscenarioswheretheloopcontinuesuntilaspecificconditionismet,usefulforuserinputsoralgorit


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

Zend Studio 13.0.1
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6
Visual web development tools
