Advertisement
Guest User

Untitled

a guest
Jun 24th, 2019
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.30 KB | None | 0 0
  1. import pygame
  2. from pygame.locals import KEYDOWN, K_SPACE, K_w, K_s, K_a, K_d,K_ESCAPE,K_SPACE, QUIT, K_LEFT, K_RIGHT
  3. import numpy as np
  4.  
  5.  
  6. import Box2D # The main library
  7. # Box2D.b2 maps Box2D.b2Vec2 to vec2 (and so on)
  8. from Box2D.b2 import (world, polygonShape, staticBody, dynamicBody,circleShape)
  9. from Box2D import (b2FixtureDef, b2PolygonShape, b2Vec2)
  10.  
  11. PPM = 15
  12. TARGET_FPS = 60
  13. TIME_STEP = 1.0/TARGET_FPS
  14. SCREEN_WIDTH, SCREEN_HEIGHT = 640 , 480
  15.  
  16. screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), 0, 32)
  17. pygame.display.set_caption('Top-Down Car')
  18. clock = pygame.time.Clock()
  19.  
  20. # Create the world
  21. GRAVITY = [0, 0]
  22. world = world(gravity=(GRAVITY), doSleep=True)
  23.  
  24. Top_Down_BodyWork_Shape = [(11.5, 0.0),
  25. (13.0, 2.5),
  26. (12.25, 5.5),
  27. (11, 7.5),
  28. (10.25, 10.0),
  29. (9.75, 10.0),
  30. (9, 7.5),
  31. (7.75, 5.5),
  32. (7.0, 2.5),
  33. (8.5, 0.0),
  34. ] # 1 Axis of symmetry
  35.  
  36. Tire_Anchoring = [(7.0, 0.75),
  37. (13.0, 0.75),
  38. (7.0, 8.50),
  39. (13.0, 8.50),
  40. ]
  41.  
  42. ### TOP DOWN CAR DEFINITION ###
  43.  
  44. Wheels = []
  45. Suspensions = []
  46.  
  47. Top_Down_BodyWork = world.CreateDynamicBody(position=(0, 0),
  48. angle=0,
  49. fixtures = b2FixtureDef(
  50. shape = b2PolygonShape(vertices=Top_Down_BodyWork_Shape),
  51. density = 2,
  52. friction = 0.3))
  53.  
  54. for i in range(4):
  55. # Create Wheels
  56. Wheels.append(world.CreateDynamicBody(position=(Tire_Anchoring[i]),
  57. angle=0,
  58. fixtures=b2FixtureDef(
  59. shape=b2PolygonShape(box=(0.5, 1.5)),
  60. density=1.0,
  61. friction = 1)))
  62.  
  63. # Anchor Wheels to Bodywork
  64.  
  65. if i in range(2):
  66. # Rear Wheels do not move so they can be welded to bodywork
  67. Suspensions.append(world.CreateWeldJoint(bodyA=Top_Down_BodyWork,
  68. bodyB= Wheels[i],
  69. localAnchorA=Tire_Anchoring[i],
  70. localAnchorB=(0,0),
  71. ))
  72. else:
  73. # Front wheels are revolute joints
  74. Suspensions.append(world.CreateRevoluteJoint(bodyA=Top_Down_BodyWork,
  75. bodyB= Wheels[i],
  76. localAnchorA=Tire_Anchoring[i],
  77. localAnchorB=(0,0),
  78. enableMotor=True,
  79. maxMotorTorque=100000,
  80. enableLimit=True,
  81. lowerAngle= -np.pi/4,
  82. upperAngle= np.pi/4,
  83. motorSpeed = 0,
  84. ))
  85.  
  86. Left_Wheel, Right_Wheel = Wheels[2], Wheels[3]
  87. Left_Susp, Right_Susp = Suspensions[2], Suspensions[3]
  88.  
  89. ### DRAWING ###
  90.  
  91. colors = {dynamicBody: (133, 187, 101, 0), staticBody: (15, 0, 89, 0)}
  92.  
  93.  
  94. def my_draw_polygon(polygon, body, fixture):
  95. vertices = [(body.transform * v) * PPM for v in polygon.vertices]
  96. vertices = [(v[0], SCREEN_HEIGHT - v[1]) for v in vertices]
  97. pygame.draw.polygon(screen, colors[body.type], vertices)
  98. polygonShape.draw = my_draw_polygon
  99.  
  100.  
  101. def my_draw_circle(circle, body, fixture):
  102. position = body.transform * circle.pos * PPM
  103. position = (position[0], SCREEN_HEIGHT - position[1])
  104. pygame.draw.circle(screen, colors[body.type], [int(
  105. x) for x in position], int(circle.radius * PPM))
  106. circleShape.draw= my_draw_circle
  107.  
  108. ### MAIN GAME LOOP ###
  109.  
  110. SteerAngle = 0
  111. Speed = 0
  112. dV = 0.01 #Speed Increment
  113.  
  114. running = True
  115. number_of_states = 0
  116. max_lateral_impulse = 30
  117. Right_Normal_Squared = []
  118. tick_counter = 0
  119.  
  120. while running:
  121. # Check the event queue
  122. for event in pygame.event.get():
  123. if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
  124. # The user closed the window or pressed escape
  125. running = False
  126.  
  127. screen.fill((255, 255, 255,0))
  128. for body in world.bodies:
  129. for fixture in body.fixtures:
  130. fixture.shape.draw(body, fixture)
  131.  
  132. # Cancelling lateral velocity
  133. for wheel in Wheels:
  134.  
  135. if wheel in range(2):
  136. continue
  137. else:
  138.  
  139.  
  140. Current_Normal = wheel.GetWorldVector((0,1))
  141. Current_N_Squared = Current_Normal.dot(wheel.linearVelocity) * Current_Normal
  142.  
  143. Right_Normal = wheel.GetWorldVector((1,0))
  144. Right_Normal_Squared = Right_Normal.dot(wheel.linearVelocity) * Right_Normal
  145.  
  146. Impulse = -Right_Normal_Squared * wheel.mass
  147. if Impulse.length >max_lateral_impulse:
  148. Impulse *= max_lateral_impulse/Impulse.length
  149.  
  150. wheel.ApplyLinearImpulse(Impulse, wheel.worldCenter, True)
  151. # Allowing skidding
  152. aimp = 0.25 * wheel.inertia * -wheel.angularVelocity
  153. wheel.ApplyAngularImpulse(aimp, True)
  154.  
  155. current_forward_speed = Current_N_Squared.Normalize()
  156.  
  157. drag_force_magnitude = -2 * current_forward_speed
  158. wheel.ApplyForce(drag_force_magnitude * Current_N_Squared,
  159. wheel.worldCenter, True)
  160.  
  161. # Top Down Car Control (WASD keys)
  162.  
  163. if event.type == KEYDOWN and event.key == K_w:
  164.  
  165. Left_Wheel.ApplyLinearImpulse(b2Vec2(10,0), Left_Wheel.position,False)
  166. Right_Wheel.ApplyLinearImpulse(b2Vec2(10,0), Left_Wheel.position,False)
  167.  
  168. elif event.type == KEYDOWN and event.key == K_s:
  169. Left_Wheel.ApplyLinearImpulse(b2Vec2(-10,0), Left_Wheel.position,True)
  170. Right_Wheel.ApplyLinearImpulse(b2Vec2(-10,0), Left_Wheel.position,True)
  171.  
  172.  
  173. if event.type == KEYDOWN and event.key==K_a:
  174. Left_Susp.motorSpeed = 1.5
  175. Right_Susp.motorSpeed = 1.5
  176.  
  177. elif event.type == KEYDOWN and event.key == K_d:
  178. Left_Susp.motorSpeed = -1.5
  179. Right_Susp.motorSpeed = -1.5
  180.  
  181. world.Step(TIME_STEP, 10, 10)
  182. tick_counter += 1
  183.  
  184. if tick_counter > TARGET_FPS:
  185. Left_Susp.motorSpeed = 0.
  186. Right_Susp.motorSpeed = 0.
  187. tick_counter = 0
  188.  
  189. pygame.display.flip()
  190. clock.tick(TARGET_FPS)
  191.  
  192. pygame.quit()
  193. print('Done!')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement