[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] car game mechanics



Three things you can do to make this more realistic.

1. use self.angle as the argument to pygame.transform.rotate instead of a_deg, as Joe suggested.

2. use separate variables to keep the car's position. Don't store it in self.rect.center. This is because rect positions are coerced to ints, so if your car should be moving 0.5 pixels per frame to the right, this will be rounded down to 0.

3. update self.rect after you transform. This is because the rotated image doesn't have the same size as the original image, so its center will be offset. Also, your second argument to screen.blit should be self.rect, not self.rect.center. (If you pass it a position like self.rect.center, it will use that as the upper-left position of the blitted rect.

I modified your file to have this in your init method:

                self.x, self.y = SCREEN_SIZE_X/2, SCREEN_SIZE_Y - self.rect.height * 2


this in your update:

                #rotate the car
                self.sprite = pygame.transform.rotate(self.original, self.angle * -1)
                self.rect = self.sprite.get_rect(center = self.rect.center)
 
                #move the car
                self.x += speedx
                self.y += speedy
               
                self.rect = self.sprite.get_rect()
                self.rect.center = self.x, self.y


and this in your draw:

                screen.blit(self.sprite, self.rect)


And it looked much better to me. Let me know what you think.

-Christopher

On Tue, Aug 30, 2011 at 5:46 AM, Nathan BIAGINI <nathan.open@xxxxxxxxx> wrote:
Hi,

i'm trying to write a car game and i have decided to start by the movement part. I calculate the X and Y components of the car and update his position by increasing the current one with the two new components. The two components depend of the orientation of the car, managed by the right and left arrow :


speedx = math.sin(self.angle * (math.pi/180)) * SPEED
speedy = math.cos(self.angle * (math.pi/180)) * SPEED * -1

Where SPEED is a constant and self.angle a int representing the orientation. I don't know if this is the best way because, the car speed depends of his orientation. Increasing the self.angle value will increase the components, this is not suitable for a car game i think.

I have another problem with the car movement. Each time the orientation change, i would like to rotate the car in the right direction. I thought to do something like that :

a_rad = math.asin(speedx/SPEED)
a_deg = math.degrees(a_rad)  
self.sprite = pygame.transform.rotate(self.original, a_deg * -1)
self.rect = self.sprite.get_rect(center = self.rect.center)

It does not work properly, this way, my car can't rotate over 90° because of the speedx values.

Here is my code :

http://pastebin.com/VJgQRtYq

and the sprite i use for the car is joined.

Thanks for reading me.