Python Pygame Camera Movement [duplicate] - python

This question already has answers here:
Add scrolling to a platformer in pygame
(4 answers)
Closed 4 years ago.
So, I'm making a 2d topviewed game in Python with Pygame. I've been trying to create a camera movement that would keep the player in the center of the screen. How would I do this? I'd like to have the "map" in a single surface, that will be blit to the screen surface. If doing so I could just build the map once and then just somehow adjust it's position so that the player will always stay in the center of the screen. My player updates it's position like this:
def update(self, dx=0, dy=0):
newpos = (self.pos[0] + dx, self.pos[1] + dy) # Calculates a new position
entityrect = pygame.Rect(newpos, self.surface.get_size()) # Creates a rect for the player
collided = False
for o in self.objects: # Loops for solid objects in the map
if o.colliderect(entityrect):
collided = True
break
if not collided:
# If the player didn't collide, update the position
self.pos = newpos
return collided
I found this, but that was for a sideviewed platformer. So my map would look something like this:
map1 = pygame.Surface((3000, 3000))
img = pygame.image.load("floor.png")
for x in range(0, 3000, img.get_width()):
for y in range(0, 3000, img.get_height()):
map1.blit(img, (x, y))
So how would I do the camera movement? Any help would be appreciated.
PS. I hope you can understand what I'm asking here, english is not my native language. =)

Well, you didn't show how you draw your map or your player, but you can do something like this:
camera = [0,0]
...
def update(self, dx=0, dy=0):
newpos = (self.pos[0] + dx, self.pos[1] + dy) # Calculates a new position
entityrect = pygame.Rect(newpos, self.surface.get_size())
camera[0] += dx
camera[1] += dy
...
Then you draw your map like this
screen.blit(map1, (0,0),
(camera[0], camera[1], screen.get_width(), screen.get_height())
)
This way the map will scroll in the opposite direction of the camera, leaving the player still.
If you wan't the player to move in your world, but not to move in the screen, you can do something like this:
screen.blit(player, (player.pos[0]-camera[0], player.pos[1]-camera[1]))

Related

Is there a way to check if a rect intersects another on a specific side? [duplicate]

This question already has an answer here:
how to know pygame.Rect's side that collide to other Rect?
(1 answer)
Closed 7 months ago.
I was wondering if there is a way to check if some rect x intersects with another rect y, but from a specific side. For eg: rect x is going upwards, and intersects with rect y. Since it was moving upwards, the function for checking if the intersection exists will return True (yes they did intersect) and "top" (top side of rect x has intersected with rect y). If there are multiple "sides" of rect x that are colliding with rect y, such as when they aren't perfectly lined up on one axis, then return the side whose length in the rect y is the longest. I will try and provide gifs to explain better.
So far I've tried:
Checking every frame for intersections (pygame.Rect.colliderect()) and the velocities of the rects
Using pygame.Rect.collidepoint() on multiple points on some side
Has anyone got any ideas? Thanks.
You can simply compare the x and y values of the rects and process the x and y axis individually.
rect_y = pygame.Rect(10, 10, 20, 20)
rect_x = pygame.Rect(10, 40, 20, 20)
def move_rect(rect, other_rect, velocity):
rect.x += velocity[0]
collision = ""
if rect.colliderect(other_rect):
if velocity[0] > 0:
collision = "right"
else:
collision = "left"
rect.y += velocity[1]
collision = ""
if rect.colliderect(other_rect):
if velocity[1] > 0:
collision = "bottom"
else:
collision = "top"
return collision
# move rect_y up by 10 pixels
move_rect(rect_y, rect_x, (0, -10))

How to rotate something by the top left in pygame [duplicate]

This question already has answers here:
How do I rotate an image around its center using Pygame?
(6 answers)
Closed 1 year ago.
Currently, I am trying to get my gun to rotate to look towards my mouse - which I have working. However the rotation is just odd and doesn't work how I want it to. I am trying to rotate it with a center of (0,0) so that it rotates around that top left corner, however it just doesn't seem to want to clamp the top left in one position and rotate around it.
What I have:
class Gun():
def __init__(self):
self.original_image = p.transform.scale(p.image.load('D:\Projects\platformer\Assets\Gun.png'),(20,8))
def rotate(self,x,y):
mx,my = p.mouse.get_pos()
rel_x,rel_y = mx - x,my - y
angle = (180/math.pi) * -math.atan2(rel_y,rel_x)
self.image = p.transform.rotate(self.original_image,int(angle))
self.rect = self.image.get_rect(center=(0,0))
WIN.blit(self.image,(x,y))
This is what is happening
yet I would want the top left of the gun to stick in just one position. Like this:
Any suggestions on how to do this, because I understand that pygame rotates weirdly and nothing I can find currently works.
You need to set the center of the bounding rectangle of the rotated image with the center of the bounding rectangle of the original image. Use the rotated rectangle to blit the image:
self.image = p.transform.rotate(self.original_image,int(angle))
self.rect = self.original_image.get_rect(topleft = (x, y))
rot_rect = self.image.get_rect(center = self.rect.center)
WIN.blit(self.image, rot_rect)
See also How do I rotate an image around its center using PyGame?

Rotating the player about the center point in pygame

I am making a game where there are two players and they can shoot each other. Their movement will be defined by a rotation around a fixed point, the point will be(600, 300), which is the center of our screen. The player will keep rotating around the point as long as they are pressing a certain button(which is keep providing force to our player) else they will fall(due to gravity). I think it would help to think of it as a ball attached to a point using a string. The string is attached as long as a button is pressed and gets unattached as soon as the button is released and the ball flies off. Here is my player class
class Player:
def __init__(self):
self.pos = [500, 200]
self.width = 30
self.height = 30
self.player = pygame.image.load("player.png").convert_alpha()
self.player = pygame.transform.scale(self.player, (self.width, self.height))
self.rect = self.player.get_rect()
self.rotated_player = None
self.anguler_vel = 0
self.Fg = 0.05
self.Fp = 0
self.arm_length = 0
Fp is the force perpendicular to the force of gravityFg. Fg is the force which is pulling it down on our player. Fp is defined by math.sin(theta) * Fg. I am keeping track of Fp because i want the player to keep moving in the direction of rotation after its unattatched from the string. arm_length is the length of the string.
I have a Point class, which is the point about which our player will rotate. Here's the point class.
class Point:
def __init__(self,x, y):
self.pos = [x, y]
dx = self.pos[0] - player.pos[0]
dy = self.pos[1] - player.pos[1]
self.angle = math.atan2(dy, dx)
Now, i need help with the actual rotation itself. I am aware that adding a certain value to the angle every single frame would make it go around. But how would i make it go around a certain point that i specify and how would the arm length tie into this?. I find that it is really difficult to implement all of this because the y-axis is flipped and all the positional values have to be scaled down when using them in calculations because of the FPS rate. Any help on how this is done would be appreciated as well. Thanks
When you use pygame.transform.rotate the size of the new rotated image is increased compared to the size of the original image. You must make sure that the rotated image is placed so that its center remains in the center of the non-rotated image. To do this, get the rectangle of the original image and set the position. Get the rectangle of the rotated image and set the center position through the center of the original rectangle. e.g.:
def rotate_center(image, rect, angle):
rotated_image = pygame.transform.rotate(image, angle)
new_rect = rotated_image.get_rect(center = rect.center)
return rotated_image, new_rect
screen.blit(*rotate_center(image, image_rect, angle))
Alos see How do I rotate an image around its center using PyGame? and How to rotate an image(player) to the mouse direction?

Pygame rect.contains collision not detecting

I am making a simple Breakout/Arkanoid game to learn pygame. I'm running into an issue where the rectangles of the paddle and the ball are not properly colliding. I also noticed that the ball doesn't collide with the bricks if I shoot the ball between two bricks, even when the ball sprite visually overlaps the bricks. This snippet if from the ball's .update method, which passes in the paddle and a list of bricks.
new_pos = self.__calc_pos()
# Check for collision with walls
if not self.area.contains(new_pos):
self.angle = -self.angle
new_pos = self.__calc_pos()
else:
# Check for collision with paddle
if paddle.rect.contains(new_pos):
self.angle = -self.angle
new_pos = self.__calc_pos()
# Check for collision with bricks
for brick in bricks:
if brick.rect.contains(new_pos):
self.angle = -self.angle
new_pos = self.__calc_pos()
brick.kill()
bricks.remove(brick)
self.rect = new_pos
The .__calc_pos method:
def __calc_pos(self):
new_x = int(math.cos(math.radians(self.angle))) * self.speed
new_y = -int(math.sin(math.radians(self.angle))) * self.speed
return self.rect.move(new_x, new_y)
contains() checks if one rect if fully inside another rect - and it doesn't true if one object only partially touch other object. Use colliderect()
contains()
test if one rectangle is inside another
contains(Rect) -> bool
Returns true when the argument is completely inside the Rect.
-
colliderect()
test if two rectangles overlap
colliderect(Rect) -> bool
Returns true if any portion of either rectangle overlap (except the top+bottom or left+right edges).

PyGame Circular Collision Issues - Circle Interior

I'm making a puzzle game that requires the user to 'draw' circles onto a background to get a ball to the exit. They create circles by holding their mouse button, the circle grows; when it is big enough, they let go and it is 'punched' into the physical space and balls then react to it.
I have a problem, however, that when two circles are intersecting (so a ball should pass through), if the intersection is not larger than the diameter of the ball the ball collides with the interior of the circle as usual.
This may be a little hard to comprehend, so here's a link to the screencast showing the problem (You can't embed videos on Stack Overflow): http://www.youtube.com/watch?v=3dKyPzqTDhs
Hopefully that made my problem clear. Here is the Python / PyGame code for the Ball and Circle classes:
class Ball():
def __init__(self, (x,y), size, colourID):
"""Setting up the new instance"""
self.x = x
self.y = y
self.size = size
self.exited = False
self.colour = setColour(colourID)
self.thickness = 0
self.speed = 0.01
self.angle = math.pi/2
def display(self, surface):
"""Draw the ball"""
# pygame.gfxdraw.aacircle(screen,cx,cy,new_dist,settings['MINIMAP_RINGS'])
if self.exited != True:
pygame.draw.circle(surface, self.colour, (int(self.x), int(self.y)), self.size, self.thickness)
def move(self):
"""Move the ball according to angle and speed"""
self.x += math.sin(self.angle) * self.speed
self.y -= math.cos(self.angle) * self.speed
(self.angle, self.speed) = module_physicsEngine.addVectors((self.angle, self.speed), gravity)
self.speed *= drag
And the Circle class:
class Circle():
def __init__(self, (x,y), size, colourID):
"""Set up the new instance of the Circle class"""
self.x = x
self.y = y
self.size = size
self.colour = setColour(colourID)
self.thickness = 2
self.angle = 0 # Needed for collision...
self.speed = 0 # detection against balls
def display(self, surface):
"""Draw the circle"""
pygame.draw.circle(surface, self.colour, (int(self.x), int(self.y)), self.size, self.thickness)
Within the main loop of the game (while running == True: etc.), this code is used to perform actions on each ball:
for b in balls:
b.move()
for i, ball in enumerate(balls):
for ball2 in balls[i+1:]:
collideBalls(ball, ball2)
collideCircle(b) # <---------------- This is the important line
collideExit(b)
b.display(screen)
And finally, the collideCircle(b) function, which is called once per ball to check for collisions with the interior of a circle, and also to check if the circles are intersecting.
def collideCircle(ball):
"""Check for collision between a ball and a circle"""
hit = False
closestDist = 0
for c in circles:
# Code cannot be replaced with physicsEngine.collideTest because it
# is slightly differnt, testing if ball [ball] inside a circle [c]
dx = c.x - ball.x
dy = c.y - ball.y
distance = math.hypot(dx, dy)
if distance <= c.size - ball.size:
# If BALL inside any CIRCLE
hit = False
break
else:
# If we're outside of a circle.
if closestDist < c.size - (distance - ball.size):
hit = c
closestDist = (c.size - (distance - ball.size))
if hit:
module_physicsEngine.circleBounce(hit, ball)
Ok, so I know that this has been a bit of a long and talky question, but I think you have all the information needed. Is the solution to make the balls interact correctly something to do with the line if distance <= c.size - ball.size:?
Anyway, thanks in advance!
Nathan out.
TL;DR - Watch the youtube video, and let me know why it's not working.
The problem is with unintended hits rather than missed ones. What you really want to check is if all parts of the ball are covered by some circle, while the check you're doing is if any circle only partially overlaps - but an override if any circle fully covers the ball.
I figure for any potential hit point, i.e. closest inner wall of a circle, let that point "walk" along the wall by checking its distance from all other circles. Should it then leave the ball, it was a false hit.
First you find the list of circles that touch the ball at all. As before, if any of them cover it, you can skip the rest of the checks. Also find the closest wall point to the ball for the circles. For each of those closest wall points, if it overlaps another circle, move it to the intersection point which is closest to the ball but further away than the current point. Discard it if it's outside the ball. Repeat the procedure for all circles, since more than two may overlap. Also note that the moving of the point may cause it to enter new circles.
You could precompute the intersection points and discard any that are a ball radius inside of any other circle.
This can surely be improved on, but it's a start, I think. I suspect a bug involving the case when both intersection points of a pair of circles overlap the ball, but a walk chain leads one of them outside the ball. Perhaps the initial collision points should be replaced only by both intersection points, not the closest.
I watched the video and I like the game principle. :)
Maybe the problem is that you break out of the loop as soon as you encounter a circle that encloses the ball. I'm referring to the snippet
if distance <= c.size - ball.size:
# If BALL inside any CIRCLE
hit = False
break
Why would you not check all of the other circles, in that case? There might be another circle yet unchecked that causes a hit.
Btw, I wouldn't say if condition == True:, that's unpythonic. Just say if condition:.

Categories

Resources