- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
一般来说是 pygame 和游戏编程的新手,只是想知道如何在自上而下的汽车游戏中让相机跟随汽车(没什么特别的)——想想 Micro Machines!我正在使用 Python 3.6,并且有一辆自行车在旋转和四处移动。我已将此处的代码缩短,但如果相机正常工作,我确实有静态图像供引用!
这是我所拥有的:
import pygame, math, sys, random
from pygame.locals import *
display_width = 1280
display_height = 800
# Sets size of screen
screen = pygame.display.set_mode((display_width, display_height))
# Initialises clock
clock = pygame.time.Clock()
# Colours
white = (255,255,255)
black = (0,0,0)
class Entity(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
class VehicleSprite(Entity):
# Creates a vehicle class
MAX_FORWARD_SPEED = 10
MAX_REVERSE_SPEED = 2
ACCELERATION = 0.05
TURN_SPEED = 0.000000000001
def __init__(self, image, position):
Entity.__init__(self)
# Creates object instance off
pygame.sprite.Sprite.__init__(self)
self.src_image = pygame.image.load(image)
self.position = position
self.speed = self.direction = 0
self.k_left = self.k_right = self.k_down = self.k_up = 0
def update(self, time):
# SIMULATION
self.speed += (self.k_up +self.k_down)
if self.speed > self.MAX_FORWARD_SPEED:
self.speed = self.MAX_FORWARD_SPEED
if self.speed < -self.MAX_REVERSE_SPEED:
self.speed = -self.MAX_REVERSE_SPEED
# Degrees sprite is facing (direction)
self.direction += (self.k_right + self.k_left)
x, y = self.position
rad = self.direction * math.pi / 180
x += -self.speed*math.sin(rad)
y += -self.speed*math.cos(rad)
self.position = (x, y)
self.image = pygame.transform.rotate(self.src_image, self.direction)
self.rect = self.image.get_rect()
self.rect.center = self.position
class Background(pygame.sprite.Sprite):
def __init__(self, image_file, location):
pygame.sprite.Sprite.__init__(self) #call Sprite initializer
self.image = pygame.image.load(image_file)
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = location
rect = screen.get_rect()
# Background
BackGround = Background('/home/pi/gametuts/images/backgrounds/bkg_img.png', [0, 0])
# Bike image load
bike = VehicleSprite('/home/pi/gametuts/images/BikePixelBig.png', rect.center)
bike_group = pygame.sprite.RenderPlain(bike)
# Ball image load
ball = VehicleSprite('/home/pi/gametuts/images/ironball.png', rect.center)
ball_group = pygame.sprite.RenderPlain(ball)
# Main game loop
def game_loop():
while 1:
#USER INPUT
# Sets frame rate
time = clock.tick(60)
for event in pygame.event.get():
if not hasattr(event, 'key'): continue
down = event.type == KEYDOWN
# Bike Input (Player 1)
if event.key == K_d: bike.k_right = down * -5
elif event.key == K_a: bike.k_left = down * 5
elif event.key == K_w: bike.k_up = down * 2
elif event.key == K_s: bike.k_down = down * -2
# Quit
elif event.key == K_ESCAPE: sys.exit(0)
#RENDERING
# Game background
screen.fill(white)
screen.blit(BackGround.image, BackGround.rect)
# Bike render
bike_group.update(time)
bike_group.draw(screen)
ball_group.update(time)
ball_group.draw(screen)
pygame.display.flip()
game_loop()
pygame.quit()
quit()
提前致谢!
最佳答案
实现相机的最简单方法是使用 pygame.math.Vector2
作为相机,每帧从中减去玩家速度,并在 blitting 期间将其添加到所有游戏元素的位置。
import pygame as pg
from pygame.math import Vector2
class Player(pg.sprite.Sprite):
def __init__(self, pos, walls, *groups):
super().__init__(*groups)
self.image = pg.Surface((30, 50))
self.image.fill(pg.Color('dodgerblue'))
self.rect = self.image.get_rect(center=pos)
self.vel = Vector2(0, 0)
self.pos = Vector2(pos)
self.walls = walls
self.camera = Vector2(0, 0)
def update(self):
self.camera -= self.vel # Change the camera pos if we're moving.
# Horizontal movement.
self.pos.x += self.vel.x
self.rect.centerx = self.pos.x
# Change the rect and self.pos coords if we touched a wall.
for wall in pg.sprite.spritecollide(self, self.walls, False):
if self.vel.x > 0:
self.rect.right = wall.rect.left
elif self.vel.x < 0:
self.rect.left = wall.rect.right
self.pos.x = self.rect.centerx
self.camera.x += self.vel.x # Also move the camera back.
# Vertical movement.
self.pos.y += self.vel.y
self.rect.centery = self.pos.y
for wall in pg.sprite.spritecollide(self, self.walls, False):
if self.vel.y > 0:
self.rect.bottom = wall.rect.top
elif self.vel.y < 0:
self.rect.top = wall.rect.bottom
self.pos.y = self.rect.centery
self.camera.y += self.vel.y
class Wall(pg.sprite.Sprite):
def __init__(self, x, y, w, h, *groups):
super().__init__(*groups)
self.image = pg.Surface((w, h))
self.image.fill(pg.Color('sienna2'))
self.rect = self.image.get_rect(topleft=(x, y))
def main():
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
all_sprites = pg.sprite.Group()
walls = pg.sprite.Group()
for rect in ((100, 170, 90, 20), (200, 100, 20, 140),
(400, 60, 150, 100), (300, 470, 150, 100)):
walls.add(Wall(*rect))
all_sprites.add(walls)
player = Player((320, 240), walls, all_sprites)
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
elif event.type == pg.KEYDOWN:
if event.key == pg.K_d:
player.vel.x = 5
elif event.key == pg.K_a:
player.vel.x = -5
elif event.key == pg.K_w:
player.vel.y = -5
elif event.key == pg.K_s:
player.vel.y = 5
elif event.type == pg.KEYUP:
if event.key == pg.K_d and player.vel.x > 0:
player.vel.x = 0
elif event.key == pg.K_a and player.vel.x < 0:
player.vel.x = 0
elif event.key == pg.K_w and player.vel.y < 0:
player.vel.y = 0
elif event.key == pg.K_s and player.vel.y > 0:
player.vel.y = 0
all_sprites.update()
screen.fill((30, 30, 30))
for sprite in all_sprites:
# Add the player's camera offset to the coords of all sprites.
screen.blit(sprite.image, sprite.rect.topleft+player.camera)
pg.display.flip()
clock.tick(30)
if __name__ == '__main__':
pg.init()
main()
pg.quit()
编辑:这是带有相机的代码示例。我还尝试改进了一些东西,例如限制速度值的 max(min(...))
技巧。我不确定机芯是否如您所愿,但您当然可以自己调整。 (我可能会对 update
方法进行更多修改。)
import math
import random
import pygame
pygame.init()
screen = pygame.display.set_mode((1280, 800))
rect = screen.get_rect()
clock = pygame.time.Clock()
WHITE = pygame.Color('white')
# Load images globally and reuse them in your program.
# Also use the `.convert()` or `.convert_alpha()` methods after
# loading the images to improve the performance.
VEHICLE1 = pygame.Surface((40, 70), pygame.SRCALPHA)
VEHICLE1.fill((130, 180, 20))
VEHICLE2 = pygame.Surface((40, 70), pygame.SRCALPHA)
VEHICLE2.fill((200, 120, 20))
BACKGROUND = pygame.Surface((1280, 800))
BACKGROUND.fill((30, 30, 30))
class Entity(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
class VehicleSprite(Entity):
MAX_FORWARD_SPEED = 10
MAX_REVERSE_SPEED = 2
ACCELERATION = 0.05
TURN_SPEED = 0.000000000001
def __init__(self, image, position):
Entity.__init__(self)
self.src_image = image
self.image = image
self.rect = self.image.get_rect(center=position)
self.position = pygame.math.Vector2(position)
self.velocity = pygame.math.Vector2(0, 0)
self.speed = self.direction = 0
self.k_left = self.k_right = self.k_down = self.k_up = 0
def update(self, time):
# SIMULATION
self.speed += self.k_up + self.k_down
# To clamp the speed.
self.speed = max(-self.MAX_REVERSE_SPEED,
min(self.speed, self.MAX_FORWARD_SPEED))
# Degrees sprite is facing (direction)
self.direction += (self.k_right + self.k_left)
rad = math.radians(self.direction)
self.velocity.x = -self.speed*math.sin(rad)
self.velocity.y = -self.speed*math.cos(rad)
self.position += self.velocity
self.image = pygame.transform.rotate(self.src_image, self.direction)
self.rect = self.image.get_rect(center=self.position)
class Background(pygame.sprite.Sprite):
def __init__(self, image, location):
pygame.sprite.Sprite.__init__(self)
self.image = image
self.rect = self.image.get_rect(topleft=location)
def game_loop():
background = Background(BACKGROUND, [0, 0])
bike = VehicleSprite(VEHICLE1, rect.center)
ball = VehicleSprite(VEHICLE2, rect.center)
bike_group = pygame.sprite.Group(bike)
ball_group = pygame.sprite.Group(ball)
all_sprites = pygame.sprite.Group(bike_group, ball_group)
camera = pygame.math.Vector2(0, 0)
done = False
while not done:
time = clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.KEYDOWN:
# Bike Input (Player 1)
if event.key == pygame.K_d:
bike.k_right = -5
elif event.key == pygame.K_a:
bike.k_left = 5
elif event.key == pygame.K_w:
bike.k_up = 2
elif event.key == pygame.K_s:
bike.k_down = -2
elif event.key == pygame.K_ESCAPE:
done = True
elif event.type == pygame.KEYUP:
if event.key == pygame.K_d:
bike.k_right = 0
elif event.key == pygame.K_a:
bike.k_left = 0
elif event.key == pygame.K_w:
bike.k_up = 0
elif event.key == pygame.K_s:
bike.k_down = 0
camera -= bike.velocity
all_sprites.update(time)
screen.fill(WHITE)
screen.blit(background.image, background.rect)
for sprite in all_sprites:
screen.blit(sprite.image, sprite.rect.topleft+camera)
pygame.display.flip()
game_loop()
pygame.quit()
关于python - 如何在pygame中让相机跟随自上而下的汽车,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45403451/
Surface.blit在 1.8 中有一个新参数:混合。定义了以下值: BLEND_ADD BLEND_SUB BLEND_MULT BLEND_MIN BLEND_MAX BLEND_RGBA_A
import sys import pygame import pygame.locals as pgl class Test: def __init__(self): pyg
我对 PyGame 比较陌生。我正在尝试制作一个简单的程序来显示表示鼠标在屏幕上的位置的字符串。 import pygame, sys from pygame.locals import * pyga
我有总是在后台运行的音乐和一些在触发时会播放声音的事件。音乐效果很好。 pygame.mixer.music.load(os.path.join(SOUND_FOLDER, 'WateryGrave.
我有这些代码 FONT = pygame.font.Font("font/calibri.ttf", 50) FONT.size = 25 但是编译器说 AttributeError: 'pygame
有我正在导入的图像: look_1 = pygame.image.load('data\\png\\look1.png').convert_alpha() 我试图减少它的大小是这样的: pygame.
我正在为我的 pygame 制作一个帮助屏幕,每当我运行它时,我都会收到此错误消息: > self.surface.blit(self.helpscreen) TypeError: argument
在 pyGame 中应用程序,我想渲染 SVG 中描述的无分辨率 GUI 小部件。 我怎样才能做到这一点? (我喜欢 OCEMP GUI 工具包,但它的渲染似乎依赖于位图) 最佳答案 这是一个完整的例
有没有办法将多首歌曲加载到 Pygame 中?我不是在谈论这样的音效; crash_sound = pygame.mixer.Sound("crash.ogg") #and pygame.mixer.
我还有一个问题。当我尝试运行我的代码时,pygame 启动然后立即停止。 这是我的代码: import pygame import os import time import random pygam
我正在使用 pymunk 和 pygame 开发一个项目。我正在使用 PivotJoint 约束将我的 body 连接在一起。如果可能的话,我想让关节不可见 - 有什么办法可以做到这一点吗?现在关节在
我使用 fedora 20、Python 2.7 和 virtualenv 1.10.1。我想在 virtualenv 中安装 pygame,我得到了 You are installing a pot
尝试将文本添加到矩形中并使用箭头键在屏幕上移动矩形。我想让文字不会超出边缘。到目前为止,我已经在没有将其放入 Rect 中的情况下工作了,但我想让 Rect 函数工作。现在文本只是反弹回来,我不知道要
我是第一次玩 pygame(总的来说我是 python 的新手),想知道是否有人可以帮助我... 我正在制作一款小型射击游戏,希望能够为坏人创建一个类。我的想法是类应该继承自 pygame.Surfa
我在 Windows 10 机器上运行了 python 3.9.1。我通过 pip 在我的机器上安装了 pygame 2.0.1 (python -m pip install https://gith
错误: File "/home/alien/cncell/core/animator.py", line 413, in create_animation_from_data pygame
这是代码。 5000 个弹跳旋转的红色方块。 (16x16 png) 在 pygame 版本上,我获得 30 fps,但使用 pyglet 获得 10 fps。对于这种事情,OpenGl 不应该更快吗
我以为 pygame.font.Font 是用来加载 .ttf 字体的,如果没有 .ttf 文件在同一个目录下就无法加载字体,但我看过一个视频,有人在没有 .ttf 文件的情况下加载字体。 ttf 字
我正在尝试使用 Travis CI 设置一个项目。项目也使用 pygame。我曾多次尝试设置它 - 但它似乎失败了。 我得到的最接近的是以下内容: .travis.yml : language: py
这个问题已经有答案了: Python error "ImportError: No module named" (38 个回答) 已关闭 3 年前。 我正在使用 Mac 并输入 pip install
我是一名优秀的程序员,十分优秀!