Again this question is on PyParticles4.
Link to last question for reference
Comment if unclear...
I am working on a Shooter game, much like this, but on a flat land with a wall that varies it's height on every turn(something for fun in the game) and with 2 players,each with a cannon that can move some distance (there's a limit, and they can't move beyond a certain amount from their start position) on each turn(the player decides if he wishes to move).
My code so far(for the Bullet and Shooter)
class Bullet(PyParticles.Particle):
def hit(self,shooterlist):
for shoot in shooterlist:
#confusion
dist = math.hypot(dx,dy)
# other funcs to added
class Shooter:
def __init__(self,pos,size):
self.rect = pygame.Rect(pos,size)
# other funcs to added
My Problems
Collision of the bullet with the Shooter. Any Ideas on how to know when the bullet collides with the rect?
I have been advised by someone to look at all the points on the edge of the rect, and see if it is within the circle but it seems to be very slow.
I think something faster would be better..
..
..
Update:
The circle can have a rect around it, which if collides with the rect, I now know when the rect is close to the circle, maybe even touching it.. How do i move forward??(Thx to PygameNerd)
I am not sure what you mean by your question, but I thingk that you need the colliderect function.
rect.colliderect(rect): Return bool
Put this in the code somewhere, and if it returns true, have the ball explode.
You can run another test every time colliderect returns true. There are a few options for what that test can be. One is similar to the advice you already received but with the wall and circle switched. Check the points on the circumference of the circle to see if one of them collides with the wall using Rect.collidepoint. In pygame, you can get a list of circumference points by creating a Mask from the circle surface and running Mask.outline. You probably won't need every point, so you could get just every Nth point. In fact, you may only need the midpoints of the edges of the circle's rect, which you can get from the Rect object itself.
You're asking for precise collision, and that would give you pixel perfect collision detection between a circle and a rectangle. You may not need it in your game, though, so I suggest trying with just colliderect first. If you're interested in collision detection in pygame in general, there are a lot of options that are directly implemented in or based on functions described in the Mask and Sprite documentation.
You can use Rect.collidepoint with the center of the circle but make rect bigger
collide_rect = Rect(x - p.radius,y - p.radius,w + 2 * p.radius,h + 2 * p.radius)
if collide_rect.collide_point(p.pos):
# Collision Resolution
Related
def death_en():
death = pygame.Surface.blit(pygame.image.load('tombstone.png'))
if x + (WarriorSize_x * .8) == x_en:
screenDisplay.blit(death, (x_en, y_en))
I'm new to Python and over all programing. I have started learning about pygame and I'm trying to create a game. What I want this function to do is to put another image on top of the enemy that was killed, though nothing happens when I get close enough to it with the main character. I now I haven't assigned a y-axis, but want to make sure this works first. I could send the whole code if it's necessary.
Thanks in advance.
To check for collisions use the PyGame Rect Class. Keep a rectangle for your player, and a rectangle for each enemy, updating the position of the rect whenever the item it tracks changes position. Also, when an enemy or the player moves, use the function Rect.colliderect() to determine if the two items have intersected on-screen.
This might be something like:
tombstone_image = pygame.image.load('tombstone.png')
...
# Inside main loop
# Have there been any collisions?
for e_rect in all_enemy_rects:
if ( e_rect.colliderect( player_rect ) ):
screenDisplay.blit( tombstone_image, e_rect )
# TODO: remove enemy from game
I dont know how to change the size of a turtle hitbox in python turtle graphics
I haven't tried anything yet because I'm new, and know very little about this. I've tried googling it, though, but nothing popped up.
from turtle import *
import turtle
from random import randint
import time
screen = turtle.Screen()
screen.setup(1920, 1080)
player = turtle.Turtle()
I want to add a button that you have to click to start right here
The game starts right here :
wn = turtle.Screen()
last_pressed = 'up'
def setup(col, x, y, w, s, shape):
player.penup()
player.up()
player.goto(x,y)
player.width(w)
player.turtlesize(s)
player.color(col)
player.lt(90)
player.down()
wn.onkey(up, "s")
wn.onkey(left, "d")
wn.onkey(right, "a")
wn.onkey(back, "w")
wn.onkey(quitTurtles, "Escape")
wn.listen()
wn.mainloop()
This may not be exactly what you are looking for, but this might work in your situation.
Detecting collision in Python turtle game
This is a thread on collision detection between objects and with some tweaking of numbers you could increase the hitbox of the turtle using the abs() function
I dont know how to change the size of a turtle hitbox in python turtle graphics
What do you mean by "hitbox"? I'm not sure what you mean by that (and neither does Google, apparently).
Do you mean that you want a rectangular button to click on? If that's the case, you could use the tkinter module together with the turtle module to create a button to click. (But be aware that it's not always easy to get the tkinter and turtle modules to work together to do what you want.)
If you want a button to click on, but don't need a Tkinter button, you could just try creating a new turtle in the shape of a rectangle that intercepts mouse clicks with onclick(). You can see an example of this if you run:
python3 -m turtledemo
and select Examples >> colormixer from the main menubar.
Or, if by "hitbox" you mean how to detect when one turtle has intercepted another turtle (as in, one has come close enough to the other to be considered a "hit"), I suggest querying each turtle's location, then using the Pythagorean Theorem to calculate the distance from each other. If this distance is within a predetermined threshold, consider the hitbox as being "hit."
You can see an example of this by typing:
python3 -m turtle
(Pay attention to the yellow turtle as he tries to catch up to the other turtle.)
I apologize if this answer isn't quite what you're looking for, but I'm just not sure what you mean by "hitbox." Maybe you could clarify?
I just saw this question today (2 years too late i know), and was having a similar problem / question.
What I ended up doing was running 3 distance checks (as i had increased my object size by 3) which differed along the x-axis (width). So it would check the distance between the ball(turtle) and the paddle (any 3 points and if it was shorter than X it would trigger the collision mechanic.
so it was something like :
check the ball class' ball object, and see how far away it is from the paddle,
and if its either in the center, or 30 pixels to the left or right of the center then hit.
if
ball.ball.distance(pad.paddle(), pad.paddle.ycor()) < 30 or
ball.ball.distance(pad.paddle.xcor() - 30, pad.paddle.ycor()) < 30 or
ball.ball.distance(pad.paddle.xcor() + 30, pad.paddle.ycor()) < 30
This question already has answers here:
Draw a transparent rectangles and polygons in pygame
(4 answers)
Closed 7 years ago.
Image showing rectangles used for collisions.
I am making an arcade-style game which involves moving an on-screen sprite. Since the in-game walls are part of the background image I have set up rectangles in order to test when a sprite collides with a wall (to block it from moving through for example). However I would like to know if there is a way to make the rectangles invisible or not viewable by the player (but still using them for collisions). I have just used the pygame.draw.rect() function to create the rectangles:
zone1rect = pygame.draw.rect(SURF, (0,0,0), (200, 418, 52, 188), 1)
EDIT: would it be possible to create a surface under the main one to add these to? And if so would this still allow collision between the sprite (which is on a different surface)?
I am not asking about aloha colours, so please do not assosciate this with another question. Also that question talks about partly transparent rectangles, not what I want to know.
You need pygame.Rect() which everybody use to keep player position, to check collision and to blit player on screen.
Player position and size
player_image = ...
player_rect = pygame.Rect(p_spritex, p_spritey, 30, 40)
check collision
player_rect.colliderect(enemy_rect)
draw player
SURF.blit(player_image, player_rect)
And you don't have to use draw.rect
prect = pygame.draw.rect(SURF, (0,0,0), (p_spritex, p_spritey, 30, 40), 1)
because it is useless
doc: pygame.Rect
tutorial: Program Arcade Games With Python And Pygame
Managed to get it to work in the end so thought I would post here to help anyone else with the same issue.
I set the rectangle variables before the "while True" line (which if you are unsure of what I mean it is the line that sets the code to run whilst the game window is actually open). Then I put the 'blit' section where all the images are set onto the surface, into a single function to run all the time. I made the rectangle variables global and simply called them in this function before the background image, which covered them:
def surface():
global zone1rect
global zone2rect
global zone3rect
global bl
global prect
zone1rect
zone2rect
zone3rect
bl
prect = pygame.draw.rect(SURF, (0,0,0), (p_spritex, p_spritey, 30, 40), 1)
SURF.blit(background,(0,0))
SURF.blit(p_sprite,(p_spritex,p_spritey))
surface()
(^The surface function)
As you can see the player rectangle (surrounding the main sprite) is made global and 'created' in this function, simply because the coordinates change depending on the player's movements so I had to treat them a little differently.
Hope this helps anyone else with this issue, especially those who are unsure of alpha colours and such :)
Is there a way in pygame for sprites, when dragged, to snap to an invisible (or visible) grid? Kinda like drag 'n drop? If so, how? I've been trying to do some sprite overlap, but it's too tedious to make an if-statement for each of the grid-lines. So how can I make a snap-to-grid drag-n-drop sprite? This is for a chess program. I'll appreciate your help.
Make an array of corners of the chess board using for loops.
corners = []
for x in range(edgeRight, edgeLeft, interval):
for y in range(edgeTop, edgeBottom, interval):
corners.append((x,y))
Then, make an event listener. When the piece is being dragged around, insert this code into whatever while statement you have:
px, py = Piece.Rect.topleft //using tuples to assign multiple vars
for cx, cy in corners:
if math.hypot(cx-px, cy-py) < distToSnap:
Piece.setPos((cx,cy))
break
I have no idea what your actual code is, but this should give you an idea. Again, pygame has no snap-to-grid functionality.
So this can be done quite simply by using the round function in python.
sprite.rect.x = ((round(sprite.rect.x/gridSquareSize))*gridSquareSize)
sprite.rect.y = ((round(sprite.rect.y/gridSquareSize))*gridSquareSize)
This manipulates the round function, by rounding your sprite's coordinates to the nearest grid square.
I'm trying to create some obstacles for the player in my program. I can't figure out how to make the sprite stop when it comes in contact with it from all sides.
I tried to use pygame.sprite.collide_rect and pygame.sprite.spritecollide, but couldn't figure out how to do it.
If you could just try to explain the concept, I'd rather try to figure the rest out myself. Thanks in advance!
def move_rect():
new_pos = player_rect.pos
new_pos = new_pos[0]+dx,new_pos[1]+dy
new_rect = rect(new_pos,player_rect.size)
for enemy in enemy_rects:
if new_rect.colliderect(enemy):
dx,dy=dx*-1,dy*-1 #reverse direction to "bounce"
#alternatively you could just return here probably
player_rect.move(dx,dy) #do the move, no collisions
something like that at least ... (I doubt it will work, its more to give you the concept)