How can I make a sprite move when key is held down
You can use pygame.key.get_pressed to do that.
example:
while running:
keys = pygame.key.get_pressed() #checking pressed keys
if keys[pygame.K_UP]:
y1 -= 1
if keys[pygame.K_DOWN]:
y1 += 1
moving a sprite while holding down a key not working
At the beginning of your code (but after you call pygame.init()
), add the following line of code:
pygame.key.set_repeat(10)
This will post keyboard events to the event queue every 10 milliseconds even if the key was already pressed.
How to make a sprite carry on moving after they key has been released
Add an attribute that indicates the direction and speed of movement. Increase the speed a small amount for each frame that the button is pressed. Scale the speed in every frame by a friction factor:
class Player:
def __init__(self):
# [...]
self.speed_x = 0
self.speed_y = 0
self.acceleration = 0.1
self.friction = 0.98
self.max_speed = 5
def move(self):
self.speed_x += self.acceleration * (keys[pg.K_RIGHT] - keys[pg.K_LEFT])
self.speed_y += self.acceleration * (keys[pg.K_DOWN] - keys[pg.K_UP])
self.speed_x = max(-self.max_speed, min(self.max_speed, self.speed_x))
self.speed_y = max(-self.max_speed, min(self.max_speed, self.speed_y))
self.pos_x += self.speed_x
self.pos_y += self.speed_y
self.rect.center = round(self.pos_x), round(self.pos_y)
self.speed_x *= self.friction
self.speed_y *= self.friction
How to make the sprite move once when arrow key is pressed?
I figured it out. Under keyReleased, set xv=0. Then when you release the arrow key, the sprite will stop moving.
Make Character Keep Moving While Key Held Down
It is a matter of Indentation. You've to apply the movement in the application loop rather than the event loop:
while True:
fpsClock.tick(FPS)
WIN.fill(WHITE)
player.draw_player(WIN)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN:
if event.key == K_UP and player.y <= 0:
player.up = True
elif event.key == K_DOWN:
player.down = True
elif event.key == K_LEFT:
player.left = True
elif event.key == K_RIGHT:
player.right = True
elif event.type == KEYUP:
if event.key == K_UP:
player.up = False
if event.key == K_DOWN:
player.down = False
if event.key == K_LEFT:
player.left = False
if event.key == K_RIGHT:
player.right = False
#<--| INDENTATION
if player.left:
player.x -= 5
if player.right:
player.x += 5
if player.up:
player.y -= 5
if player.down:
player.y += 5
pygame.display.update()
Alternatively you can use pygame.key.get_pressed()
rather than the KEYDOWN
and KEYUP
event:
while True:
fpsClock.tick(FPS)
WIN.fill(WHITE)
player.draw_player(WIN)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
keys = pygame.key.get_pressed()
player.left, player.right, player.up, player.down = False, False, False, False
if keys[K_LEFT]:
player.x -= 5
player.left = True
if keys[K_RIGHT]:
player.x += 5
player.right = True
if keys[K_UP]:
player.y -= 5
player.up = True
if keys[K_DOWN]:
player.y += 5
player.down = True
pygame.display.update()
To control the animation speed, add an attribute self.animation_frames = 10
. This attributes controls how many frames each image of the animation is shown. Compute the image index dependent on the attribute.walking_count
has to be incremented in Player.draw_player
rather than the application loop.
To ensure that the correct "standing" image is displayed, you have to add an attribute self.standing
. Set the attribute dependent on the current direction in draw_player
. If the player is not moving, the display the current standing image:
class Player:
def __init__(self, x, y):
# [...]
self.animation_frames = 10
self.standing = standing_left
def draw_player(self, win):
# get image list
if self.left:
image_list = left
self.standing = standing_left
else self.right:
image_list = right
self.standing = standing_right
else:
image_list = [self.standing]
# increment walk count and get image list
image_index = self.walking_count // self.animation_frames
if image_index >= len(image_list):
image_index = 0
self.walking_count = 0
self.walking_count += 1
WIN.blit(image_list[image_index], (self.x, self.y))
Java Move Sprite Constantly While Key Binding is Pressed
Is there a way to prevent to the hesitation of the movement.
You can use a Swing Timer to schedule the animation. Check out Motion Using the Keyboard for a working example.
Python sprite not moving when key is held down
Generally you blit() images on to the screen (pygame.display.set_mode()
), for the changes to to reflect on the screen we call pygame.display.update()
, In your case the game never comes the statement, which is out of while loop.
Pygame sprite not moving when key pressed
There are some mistakes. The first mistake is a typo. It has to be event.key
rather than pygame.key
.
Also, you must blit
the sprite in the application loop, not the event loop, in the location stored in rect
. Get the rectangle (rect
) before the loop. Move the rectangle in the event loop and blit
the sprite in every frame at rect
:
rect = sprite1.get_rect()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
rect = rect.move(1, 0)
elif event.key == pygame.K_LEFT:
rect = rect.move(-1, 0)
screen.blit(background_image, (0, 0))
screen.blit(sprite1, rect)
pygame.display.flip()
pygame.quit()
exit()
Note, you can use move_ip()
rather than move
:
rect = rect.move((-1, 0))
rect.move_ip(-1, 0)
However, use pygame.key.get_pressed()
for a continuous movement:
rect = sprite1.get_rect()
speed = 1
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
rect.x += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * speed
rect.y += (keys[pygame.K_DOWN] - keys[pygame.K_UP]) * speed
screen.blit(background_image, (0, 0))
screen.blit(sprite1, rect)
pygame.display.flip()
pygame.quit()
exit()
The keyboard events (see pygame.event module) occur only once when the state of a key changes. The KEYDOWN
event occurs once every time a key is pressed. KEYUP
occurs once every time a key is released. Use the keyboard events for a single action or a step-by-step movement.
pygame.key.get_pressed()
returns a list with the state of each key. If a key is held down, the state for the key is True
, otherwise False
. Use pygame.key.get_pressed()
to evaluate the current state of a button and get continuous movement.
Complete example:
import pygame
icon1 = pygame.image.load("Firstpygamegame/santa-claus.png")
pygame.display.set_icon(icon1)
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Gift Catcher")
clock = pygame.time.Clock()
background_image = pygame.image.load("Firstpygamegame/wintervillage.png")
sprite1 = pygame.image.load("Firstpygamegame/santabag2.png")
rect = sprite1.get_rect()
speed = 1
running = True
while running:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
rect.x += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * speed
rect.y += (keys[pygame.K_DOWN] - keys[pygame.K_UP]) * speed
screen.blit(background_image, (0, 0))
screen.blit(sprite1, rect)
pygame.display.flip()
pygame.quit()
exit()
Related Topics
H14 Error in Heroku - "No Web Processes Running"
Shebang Notation: Python Scripts on Windows and Linux
Call Python Script from Bash With Argument
Python Script as Linux Service/Daemon
Integer Division by Negative Number
How to Select Rows from a Dataframe Based on Column Values
Get the Data Received in a Flask Request
Why Does This Unboundlocalerror Occur (Closure)
How to Sort a Dictionary by Key
How to Split a String into a List
Pygame Installation Issue in MAC Os
What Does the Star and Doublestar Operator Mean in a Function Call
How to Find All Occurrences of an Element in a List
How to Read a Large CSV File With Pandas
How to Run Your Own Code Alongside Tkinter'S Event Loop
What Is the Python "With" Statement Designed For
Import Multiple CSV Files into Pandas and Concatenate into One Dataframe