模拟汽车运行。前轮转动不同角度汽车运行状态。代码还存在较多bug, 暂不处理....
import pygame
import os
import numpy as np
from shapely.geometry import Point,LineString
import matplotlib.pyplot as plt
import matplotlib.patches as mpathes
import pygame,sys,time,random
from pygame.locals import *
class Point(object):
x = 0
y = 0
def __init__(self, x=0, y=0):
self.x = x
self.y = y
print("x:",x," y:",y)
def GetCenterPoint(Point1,Point2,angle):
car_length = np.sqrt(np.square(Point1.y - Point2.y) + np.square(Point1.x-Point2.x))
length = car_length/np.tan(angle*np.pi/180)
length2 = car_length/np.sin(angle*np.pi/180)
if(Point1.x-Point2.x == 0):
center_x = Point2.x - length;
center_y = Point2.y
else:
car_angle = np.arctan((Point1.y-Point2.y)/(Point1.x-Point2.x))
length_angle = car_angle + np.pi/2
center_x = Point2.x - length * np.cos(length_angle)
center_y = Point2.y - length * np.sin(length_angle)
print("center_x:",center_x,"center_y:",center_y)
return center_x,center_y,length2
WINDOW_W, WINDOW_H = 1280, 720
p1 = Point(WINDOW_W/2+300.0,WINDOW_H/2-50)
p3 = Point(WINDOW_W/2+300.0,WINDOW_H-200.0)
FPS = 100 # 帧率,即每秒刷新多少次
pygame.init() # 初始化pygame
# 设置窗口出现的位置
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (200,100)
# 创建一个窗口
screen = pygame.display.set_mode((WINDOW_W, WINDOW_H), pygame.DOUBLEBUF, 32)
# 设置窗口标题
pygame.display.set_caption("hello,car!")
# 创建时钟对象 (可以控制游戏循环频率)
clock = pygame.time.Clock()
car_image = pygame.image.load('car.png')
car_rect = car_image.get_rect()
car_rect = car_rect.move(p1.x,p1.y)
# 定义main函数
def main():
angle = 45
center_x,center_y,length = GetCenterPoint(p1,p3,angle)
x, y = 0,0
rotation_angle = 0
# 游戏主循环
while True:
# 遍历事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
# 接收到退出事件后退出程序
exit()
elif event.type == KEYDOWN:
if event.key == K_RIGHT:
pass
if event.key == K_LEFT:
pass
# 将背景图画上去(0,0,0)为RGB颜色
new_car = pygame.transform.rotate(car_image, rotation_angle)
screen.fill((255, 255, 255))
new_car_rect = new_car.get_rect(center=car_rect.center)
new_car_rect = new_car_rect.move(x,y)
rotation_angle += 1
x = length - length *np.cos(rotation_angle*np.pi/180)
x = -x
y = length * np.sin(rotation_angle*np.pi/180)
y = -y
#rotate_angle += 1
screen.blit(new_car,new_car_rect)
# 刷新画面
pygame.display.update()
# 设置FPS
time_passed = clock.tick(FPS)
if __name__ == '__main__':
print("hello")
main()