This question already has answers here:
Image rotation while moving
(2 answers)
Move Character with Vector
(2 answers)
Closed 2 years ago.
I'm attempting to move a character so that they face the mouse when I move it; I understand the concept but am completely at a loss at how to code it. At the moment, I understand how to rotate the character separately and how to move the character separately. Is it possible for me to merge the two so that I may both move and rotate my character with keys and my mouse?
These are my defined variables:
xPlayer = 25
yPlayer = 25
dxPlayer = 0
dyPlayer = 0
playerPosition = (25,25)
This is the portion that allows the image to rotate in the direction of the mouse:
go = True
while go:
position = pygame.mouse.get_pos()
screen.blit(nightBackground, (0,0))
mousePosition = pygame.mouse.get_pos()
angle = math.atan2(mousePosition[1]-(playerPosition[1]+32),mousePosition[0]-(playerPosition[0]+26))
playerRotate = pygame.transform.rotate(peterPlayer, 360-angle*57.29)
playerpos1 = (playerPosition[0]-playerRotate.get_rect().width/2, playerPosition[1]-playerRotate.get_rect().height/2)
screen.blit(playerRotate, playerpos1)
pygame.display.update()
And this is the portion for controlling my character with the keys:
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
dxPlayer = -15
elif event.key == pygame.K_RIGHT:
dxPlayer = 15
elif event.key == pygame.K_UP:
dyPlayer = -15
elif event.key == pygame.K_DOWN:
dyPlayer = 15
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
dxPlayer = 0
elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
dyPlayer = 0
xPlayer = xPlayer + dxPlayer
yPlayer = yPlayer + dyPlayer
pygame.display.update()
Any help is greatly appreciated!
Related
This question already has answers here:
How to rotate an image(player) to the mouse direction?
(2 answers)
How do I make my player rotate towards mouse position?
(1 answer)
Closed 9 months ago.
This post was edited and submitted for review 9 months ago and failed to reopen the post:
Original close reason(s) were not resolved
so im making a top down shooter game and i want to make the player face the mouse at all times. whenever i search it up, i cant figure out what the answer actually means. ive tried:
mouseY, mouseX = pygame.mouse.get_pos()
angle_to_pointer = math.degrees(math.atan2(T_rect.y - mouseY, T_rect.x - mouseX)) + 180
but that only makes it spin uncontrollably off the screen.
heres my main loop:
run = True
while run:
screen.blit(Tonk,(T_rect))
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
pr_l = True
if event.key == pygame.K_RIGHT:
pr_r = True
if event.key == pygame.K_UP:
pr_u = True
if event.key == pygame.K_DOWN:
pr_d = True
if event.key == pygame.K_SPACE:
pr_s = True
elif event.type == pygame.KEYUP: # check for key releases
if event.key == pygame.K_LEFT: # left arrow turns left
pr_l = False
elif event.key == pygame.K_RIGHT: # right arrow turns right
pr_r = False
elif event.key == pygame.K_UP: # up arrow goes up
pr_u = False
elif event.key == pygame.K_DOWN: # down arrow goes down
pr_d = False
elif event.key == pygame.K_SPACE:
pr_s = False
elif event.type == pygame.MOUSEMOTION:
m_m = True
if pr_l == True:
screen.fill(colour)
T_rect.x -= speed
screen.blit(Tonk,(T_rect))
if pr_r == True:
screen.fill(colour)
T_rect.x += speed
screen.blit(Tonk,(T_rect))
if pr_u == True:
screen.fill(colour)
T_rect.y -= speed
screen.blit(Tonk,(T_rect))
if pr_d == True:
screen.fill(colour)
T_rect.y += speed
screen.blit(Tonk,(T_rect))
if m_m == True:
screen.fill(colour)
screen.blit(Tonk,(T_rect))
pygame.display.flip()
clock.tick(60)
please help?
Edit: answered on my previous question: how can i make an image point towards the mouse in python
This question already has answers here:
How to detect collisions between two rectangular objects or images in pygame
(1 answer)
Pygame - How to make hitbox work with enemy movement? [duplicate]
(1 answer)
Closed 2 years ago.
I was wondering how to do collision detection in pygame. My game doesn't use sprites, it just blits 2 images. How could I check if they are colliding? I know there is sprite.collide, but it doesn't use sprites. Is there some way to check collision by comparing the x and y values of each image?
def fish(x,y):
gameDisplay.blit(fishImg,(x,y))
def enemy(enemyX,enemyY):
gameDisplay.blit(enemyImg,(enemyX,enemyY))
def main():
x = displayWidth/2
y = displayHeight/2
enemyX = random.randint(0,displayWidth)
enemyY = random.randint(0,displayHeight)
xChange = 0
yChange = 0
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
xChange = -5
elif event.key == pygame.K_d:
xChange = 5
elif event.key == pygame.K_w:
yChange = -5
elif event.key == pygame.K_s:
yChange = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_a or event.key == pygame.K_d:
xChange = 0
elif event.key == pygame.K_w or event.key == pygame.K_s:
yChange = 0
x += xChange
y += yChange
gameDisplay.fill(red)
fish(x,y)
enemy(enemyX,enemyY)
if
pygame.display.update()
clock.tick(30)
main()
pygame.quit()
quit()
Use pygame.Rect and colliderect() to check for collision.
Create pygame.Rect objects, with the size of the image and the location, where you have blit the images.
pygame.Surface.get_rect() creates a pygame.Rect object at position (0, 0), but the top left position can be set by the keyword argument topleft:
fishRect = fishImg.get_rect(topleft = (x, y))
enemyRect = enemyImg.get_rect(topleft = (enemyX, enemyY))
if fishRect.colliderect(enemyRect):
# [...] collision detected
I have to blink(on and off) 2 circles alternatively using pygame. How to make it blink using pygame.
for event in pygame.event.get():
blueball = pygame.draw.circle(screen, b, (175,100),20,3)
redball = pygame.draw.circle(screen, r, (675,350),20,3)
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
bluebally += 5
redballx +=5
if event.key == pygame.K_DOWN:
bluebally += 5
redballx +=5
if event.key == pygame.K_RIGHT:
blueballx += 5
redbally +=5
if event.key == pygame.K_RIGHT:
blueballx += 5
redbally +=5
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
screen.blit(blueball,(blueballx,bluebally))
screen.blit(redball,(redballx,redbally))
I expect blue ball and redball blink alternatively
I don't know your full code, but let me know if this helps you:
Somewhere before the drawing function
color_cycle_index = 0
Then in your drawing function
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
bluebally += 5
redballx +=5
if event.key == pygame.K_DOWN:
bluebally += 5
redballx +=5
if event.key == pygame.K_RIGHT:
blueballx += 5
redbally +=5
if event.key == pygame.K_RIGHT:
blueballx += 5
redbally +=5
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if color_cycle_index % 2 == 0:
# draw red
pygame.draw.circle(screen, r, (redballx, redbally), 20, 3)
else:
# draw blue
pygame.draw.circle(screen, b, (blueballx, bluebally), 20, 3)
color_cycle_index += 1 # <-- it's better to increase this every n seconds instead of every frame
This question already has answers here:
How can I make a sprite move when key is held down
(6 answers)
How to get if a key is pressed pygame [duplicate]
(1 answer)
Closed 2 years ago.
After hitting a and d or left and right key , the sprite will still move without me pressing the key.He just won't stop.How can i fix this?
def control(self, x, y):
'''
control player movement
'''
self.movex += x
self.movey += y
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT or event.key == ord('a'):
player.control(-steps , 0)
if event.key == pygame.K_RIGHT or event.key == ord('d'):
player.control(steps , 0)
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == ord('a'):
player.control(0 , 0)
if event.key == pygame.K_RIGHT or event.key == ord('d'):
player.control(0 , 0)
I've been getting the error :
line 102, in <module>
shot[2] += shoty
IndexError: list index out of range
In my code where I am trying to code a dagger to be thrown, and deleted if it is out of bounds. I understand what the list error means however; I am unsure of how it is affecting my code and any help would be greatly appreciated!
This is the part of my code which is relevant to the problem:
daggers = []
daggerPlayer = pygame.image.load(daggerImage.png)
for shot in daggers:
index = 0
shotx = math.cos(shot[0])*10
shoty = math.sin(shot[0])*10
shot[1] += shotx
shot[2] += shoty
if (shot[1] < -64) or (shot[1] > 900) or (shot[2] < -64) or (shot[2]> 600):
daggers.pop(index)
index +=1
for shoot in daggers:
daggerOne = pygame.transform.rotate(daggerPlayer, 360 - shoot[0]*57.29)
screen.blit(daggerOne, (shoot[1], shoot[2]))
EDIT: Here is the entirety of my code
#Load Images
peterPlayer = pygame.image.load('pixelPirateOne.png)'
nightBackground = pygame.image.load ('NightSky.png')
daggerPlayer = pygame.image.load('daggerImage.png')
#Settting Variables for Moving Character
xPlayer = 200
yPlayer = 275
dxPlayer = 0
dyPlayer = 0
playerPosition = (200,275)
accuracyShot = [0,0]
daggers = []
def quitGame():
pygame.quit()
sys.exit()
go = True
while go:
#Blit The Background
screen.blit(nightBackground, (0,0))
#Learned about atan2 from --> https://docs.python.org/2/library/math.html
#Allows To Rotate Player With Mouse
mousePosition = pygame.mouse.get_pos()
angle = math.atan2(mousePosition[1]-(yPlayer+32),mousePosition[0]-(xPlayer+26))
playerRotate = pygame.transform.rotate(peterPlayer, 360-angle*57.29)
playerPositionNew = (xPlayer-playerRotate.get_rect().width/2, yPlayer-playerRotate.get_rect().height/2)
screen.blit(playerRotate, playerPositionNew)
pygame.display.update()
#Quit Game
for event in pygame.event.get():
if event.type == pygame.QUIT:
quitGame()
#Move Player- Note: Make this portion fluid; it's choppy as of now
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
dxPlayer -= 15
elif event.key == pygame.K_RIGHT:
dxPlayer += 15
elif event.key == pygame.K_UP:
dyPlayer -= 15
elif event.key == pygame.K_DOWN:
dyPlayer += 15
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
dxPlayer = 0
elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
dyPlayer = 0
xPlayer = xPlayer + dxPlayer
yPlayer = yPlayer + dyPlayer
pygame.display.update()
if event.type == pygame.MOUSEBUTTONDOWN:
mousePosition = pygame.mouse.get_pos()
accuracyShot[1] += 1
daggers.append([math.atan2(mousePosition[1]-(playerPositionNew[1]+32), mousePosition[0]-(playerPositionNew[0]+26)), playerPositionNew[1]+32])
#Learned about cos and sin in python from --> https://docs.python.org/2/library/math.html
#Learned about .pop from --> https://docs.python.org/2/tutorial/datastructures.html
for shot in daggers:
index = 0
shotx = math.cos(shot[0])*10
shoty = math.sin(shot[0])*10
shot[1] += shotx
shot[2] += shoty
if (shot[1] < -64) or (shot[1] > 900) or (shot[2] < -64) or (shot[2]> 600):
daggers.pop(index)
index +=1
for shoot in daggers:
daggerOne = pygame.transform.rotate(daggerPlayer, 360 - shoot[0]*57.29)
screen.blit(daggerOne, (shoot[1], shoot[2]))
The list you append to daggers has only two elements, but by calling shot[2] you are trying to access the third, that's why you get that error. The two elements should be shot[0] and shot[1]. I believe you make the same mistake in screen.blit(daggerOne, (shoot[1], shoot[2])) as well.