Ejemplo n.º 1
0
    def __init__(self):
        if Missile.missile_mesh is None:
            Missile.missile_mesh = Missile.create_missile_mesh()
            Missile.missile_material = Material(Color(1, 0, 0, 1),
                                                "MissileMaterial")

        super().__init__("Missile")

        # Determine the spawn position. There's 33% chance it comes from the right, 33% that it
        # comes from behind the mountains, and 34% chance it comes from the left
        self.position = Vector3(0, random.uniform(0, 3), 12)
        r = random.uniform(0, 100)
        if r > 66:
            self.position.x = 7
            self.rotation = Quaternion.AngleAxis(Vector3(0, 1, 0),
                                                 math.radians(-90))
        elif r > 33:
            self.position.y = -2
            self.position.x = random.uniform(-4, 4)
            self.rotation = Quaternion.AngleAxis(Vector3(1, 0, 0),
                                                 math.radians(-90))
        else:
            self.position.x = -7
            self.rotation = Quaternion.AngleAxis(Vector3(0, 1, 0),
                                                 math.radians(90))

        # Set the mesh and material of the missile
        self.mesh = Missile.missile_mesh
        self.material = Missile.missile_material
        # Sets the missile linear speed
        self.missile_speed = 2
        # Sets the rotation speed (in radians per second)
        self.missile_rotation_speed = 0.75
Ejemplo n.º 2
0
    def update(self, delta_time):
        """Animates the missile."""
        # Moves missile based on its direction (the forward vector)
        velocity = self.forward() * self.missile_speed
        self.position += velocity * delta_time

        # Rotate missile towards the player - Figure out where it is pointing and
        # where do we want to point it
        current_dir = self.forward()
        desired_dir = (Vector3(0, 0, 0) - self.position).normalized()
        # Find the angle between these two directions
        dp = max(-1, min(1, dot_product(current_dir, desired_dir)))
        angle = math.acos(dp)

        # If the angle is larger than the ammount we can rotate a single frame,
        # given by the time elapsed and the missile rotation speed, we need to
        # clamp the value of the angle
        if abs(angle) > self.missile_rotation_speed * delta_time:
            angle = self.missile_rotation_speed * delta_time * math.copysign(
                1, angle)

        # Figure out the rotation axis to point the missile towards the desired direction
        axis = cross_product(current_dir, desired_dir)
        axis.normalize()

        if (angle > 0.01):
            # Rotate the missile towards the player
            q = Quaternion.AngleAxis(axis, angle)
            self.rotation = q * self.rotation
Ejemplo n.º 3
0
    def rotate_angle(self, angle):
        """Rotates the ball to a certain angle, parallel to the ground

        Args:
            angle (Vector3): Angle in degrees to snap the rotation to
        """
        self.rotation = Quaternion.AngleAxis(Vector3(0, 0, 1), angle)
Ejemplo n.º 4
0
    def update(self, delta_time):
        """Animates the cube, accelerating it with gravity and rotating it."""
        self.velocity += GRAVITY * delta_time
        self.position.y += self.velocity * delta_time

        q = Quaternion.AngleAxis(self.rotation_axis,
                                 self.rotation_speed * delta_time)
        self.rotation = q * self.rotation
Ejemplo n.º 5
0
    def update_behaviour(self, delta):

        # Do nothing but check for input if not active
        if not self.active:
            self.buffer_count += 1 * delta
            keys = pygame.key.get_pressed()
            if keys[self.
                    ACTIVATE_BALL_KEY] and self.buffer_count >= self.INPUT_BUFFER:
                self.active = True
            return

        # Update the score display
        self.score_number_display.text = str(
            ScoreKeeper.current_score) + " (x" + str(self.combo) + ")"

        # Rotate over itself to show ball speed
        self.rotation = Quaternion.AngleAxis(
            self.up(),
            20 * math.radians(delta * self.ball_speed)) * self.rotation

        # Keep it aligned with the "ground"
        self.position.z = 0

        # Reset the list of unhandled collisions, since we're not even colliding
        if not self.my_collider.is_colliding:
            self.handled_collisions = []

        # Move the ball
        self.position += self.ball_speed * self.direction_vector.normalized(
        ) * delta

        # If ball falls under the screen, reset it
        if self.position.y < self.LOWER_LIMIT:
            print("Ball Reset")
            ScoreKeeper.current_score += ScoreKeeper.SCORE_DEATH_PENALTY
            self.reset_ball()
Ejemplo n.º 6
0
def main():
    """Main function, it implements the application loop"""
    # Initialize pygame, with the default parameters
    pygame.init()

    # Define the size/resolution of our window
    res_x = 640
    res_y = 480

    # Create a window and a display surface
    screen = pygame.display.set_mode((res_x, res_y))

    # Create a scene
    scene = Scene("TestScene")
    scene.camera = Camera(False, res_x, res_y)

    # Moves the camera back 2 units
    scene.camera.position -= Vector3(0, 0, 2)

    # Create a sphere and place it in a scene, at position (0,0,0)
    obj1 = Object3d("TestObject")
    obj1.scale = Vector3(1, 1, 1)
    obj1.position = Vector3(0, 0, 0)
    obj1.mesh = Mesh.create_sphere((1, 1, 1), 12, 12)
    obj1.material = Material(Color(1, 0, 0, 1), "TestMaterial1")
    scene.add_object(obj1)

    # Specify the rotation of the object. It will rotate 15 degrees around the axis given,
    # every second
    angle = 0
    axis = Vector3(0, 1, 0)
    axis.normalize()

    # Timer
    delta_time = 0
    prev_time = time.time()

    pygame.mouse.set_visible(True)
    pygame.event.set_grab(False)

    # Game loop, runs forever
    while True:
        # Process OS events
        for event in pygame.event.get():
            # Checks if the user closed the window
            if event.type == pygame.QUIT:
                # Exits the application immediately
                return
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    return

        # Clears the screen with a very dark blue (0, 0, 20)
        screen.fill((0, 0, 0))

        # Rotates the object, considering the time passed (not linked to frame rate)
        q = Quaternion.AngleAxis(axis, math.radians(angle) * delta_time)
        obj1.rotation = q * obj1.rotation

        scene.render(screen)

        # Swaps the back and front buffer, effectively displaying what we rendered
        pygame.display.flip()

        # Updates the timer, so we we know how long has it been since the last frame
        delta_time = time.time() - prev_time
        prev_time = time.time()

        #Variavel que vai guardar a tecla pressionada
        k = pygame.key.get_pressed()

        #Cada tecla tem a sua própria ação
        if (k[pygame.K_UP]):
            angle = 15
            axis = Vector3(1, 0, 0)
        elif (k[pygame.K_DOWN]):
            angle = -15
            axis = Vector3(1, 0, 0)
        elif (k[pygame.K_LEFT]):
            angle = 15
            axis = Vector3(0, 1, 0)
        elif (k[pygame.K_RIGHT]):
            angle = -15
            axis = Vector3(0, 1, 0)
        elif (k[pygame.K_PAGEUP]):
            angle = 15
            axis = Vector3(0, 0, 1)
        elif (k[pygame.K_PAGEDOWN]):
            angle = -15
            axis = Vector3(0, 0, 1)
        elif (k[pygame.K_w]):
            obj1.position.y = obj1.position.y + 0.001
        elif (k[pygame.K_s]):
            obj1.position.y = obj1.position.y - 0.001
        elif (k[pygame.K_a]):
            obj1.position.x = obj1.position.x - 0.001
        elif (k[pygame.K_d]):
            obj1.position.x = obj1.position.x + 0.001
        elif (k[pygame.K_q]):
            obj1.position.z = obj1.position.z + 0.001
        elif (k[pygame.K_e]):
            obj1.position.z = obj1.position.z - 0.001
        else:
            angle = 0
Ejemplo n.º 7
0
def main():
    """Main function, it implements the application loop"""
    # Initialize pygame, with the default parameters
    pygame.init()

    # Define the size/resolution of our window
    res_x = 640
    res_y = 480

    # Create a window and a display surface
    screen = pygame.display.set_mode((res_x, res_y))

    # Create a scene
    scene = Scene("TestScene")
    scene.camera = Camera(False, res_x, res_y)

    # Moves the camera back 2 units
    scene.camera.position -= Vector3(0, 0, 4)

    # Create a sphere and place it in a scene, at position (0,0,0)
    '''
    obj1 = Object3d("TestObject")
    obj1.scale = Vector3(1, 1, 1)
    obj1.position = Vector3(0, 0, 0)
    obj1.mesh = Mesh.create_sphere((1, 1, 1), 12, 12)
    obj1.material = Material(Color(1, 0, 0, 1), "TestMaterial1")
    scene.add_object(obj1)
    '''
    # puts name of file that you wanna load
    # if you dont want to load a file leave it as ""
    fileloaded = "teste2.obj"

    #if theres so file to be loaded
    if fileloaded == "":
        # Create a pyramid and place it in a scene, at position (0,0,0)
        obj1 = Object3d("TestObject")
        obj1.scale = Vector3(1, 1, 1)
        obj1.position = Vector3(0, 0, 0)
        obj1.mesh = Mesh.create_pyramid()
        obj1.material = Material(Color(1, 0, 0, 1), "TestMaterial1")
        scene.add_object(obj1)

    else:
        # Create a object chosen by the user and place it in a scene, at position (0,0,0)
        obj1 = Object3d("TestObject")
        obj1.scale = Vector3(1, 1, 1)
        obj1.position = Vector3(0, 0, 0)

        #function to enable objects to be loaded from terminal
        if len(sys.argv) == 2:
            print(True)
            obj1.mesh = Mesh.create_mesh(sys.argv[1])
        #if nothing at the terminal just run normaly with the name of the file in code
        else:
            obj1.mesh = Mesh.create_mesh(fileloaded)
        # add object to viewer
        obj1.material = Material(Color(1, 0, 0, 1), "TestMaterial1")
        scene.add_object(obj1)

    # Specify the rotation of the object. It will rotate 15 degrees around the axis given,
    # every second
    angle = 50
    axis = Vector3(1, 0.7, 0.2)
    axis.normalize()

    # Timer
    delta_time = 0
    prev_time = time.time()

    pygame.mouse.set_visible(True)
    pygame.event.set_grab(False)

    # Game loop, runs forever
    while True:
        # Process OS events
        for event in pygame.event.get():
            # Checks if the user closed the window
            if event.type == pygame.QUIT:
                # Exits the application immediately
                return
            #if your pressing a key
            elif event.type == pygame.KEYDOWN:
                #exit the game
                if event.key == pygame.K_ESCAPE:
                    return
                # rotate object in y axis
                if event.key == pygame.K_LEFT:
                    axis = Vector3(0, 1, 0)
                if event.key == pygame.K_RIGHT:
                    axis = Vector3(0, -1, 0)
                # rotate object in x axis
                if event.key == pygame.K_UP:
                    axis = Vector3(1, 0, 0)
                if event.key == pygame.K_DOWN:
                    axis = Vector3(-1, 0, 0)
                # rotate object in z axis
                if event.key == pygame.K_PAGEUP:
                    axis = Vector3(0, 0, 1)
                if event.key == pygame.K_PAGEDOWN:
                    axis = Vector3(0, 0, -1)
                #normalize axis
                axis.normalize()

        # Clears the screen with a very dark blue (0, 0, 20)
        screen.fill((0, 0, 0))

        # Rotates the object, considering the time passed (not linked to frame rate)
        ax = (axis * math.radians(angle) * delta_time)

        q = Quaternion.AngleAxis(axis, math.radians(angle) * delta_time)

        #Object movement
        keys = pygame.key.get_pressed()
        # movementing object up down right and left
        if keys[pygame.K_LEFT]:
            obj1.rotation = q * obj1.rotation
        if keys[pygame.K_RIGHT]:
            obj1.rotation = q * obj1.rotation
        if keys[pygame.K_UP]:
            obj1.rotation = q * obj1.rotation
        if keys[pygame.K_DOWN]:
            obj1.rotation = q * obj1.rotation

        #functions to make the rotations work
        if keys[pygame.K_PAGEUP]:
            obj1.rotation = q * obj1.rotation
        if keys[pygame.K_PAGEDOWN]:
            obj1.rotation = q * obj1.rotation
        if keys[pygame.K_w]:
            obj1.position = Vector3(obj1.position.x, obj1.position.y + 0.006,
                                    obj1.position.z)
        if keys[pygame.K_s]:
            obj1.position = Vector3(obj1.position.x, obj1.position.y - 0.006,
                                    obj1.position.z)
        if keys[pygame.K_a]:
            obj1.position = Vector3(obj1.position.x - 0.006, obj1.position.y,
                                    obj1.position.z)
        if keys[pygame.K_d]:
            obj1.position = Vector3(obj1.position.x + 0.006, obj1.position.y,
                                    obj1.position.z)
        if keys[pygame.K_q]:
            obj1.position = Vector3(obj1.position.x, obj1.position.y,
                                    obj1.position.z - 0.006)
        if keys[pygame.K_e]:
            obj1.position = Vector3(obj1.position.x, obj1.position.y,
                                    obj1.position.z + 0.006)

        #rendering objects on to screen
        scene.render(screen)

        # Swaps the back and front buffer, effectively displaying what we rendered
        pygame.display.flip()

        # Updates the timer, so we we know how long has it been since the last frame
        delta_time = time.time() - prev_time
        prev_time = time.time()
Ejemplo n.º 8
0
def main():
    """Main function, it implements the application loop"""

    # Initialize pygame, with the default parameters
    pygame.init()

    # Define the size/resolution of our window
    res_x = 1280
    res_y = 720

    # Create a window and a display surface
    screen = pygame.display.set_mode((res_x, res_y))

    # Create a scene
    scene = Scene("TestScene")
    scene.camera = Camera(False, res_x, res_y)

    # Moves the camera back 2 units
    scene.camera.position -= Vector3(0, 0, 0)

    # Specify the rotation of the object. It will rotate 15 degrees around the axis given, every second
    axis = scene.camera.up()
    axis.normalize()

    # Timer
    delta_time = 0
    prev_time = time.time()

    # Show mouse cursor
    pygame.mouse.set_visible(False)
    # Don't lock the mouse cursor to the game window
    pygame.event.set_grab(True)
    
    #Clean count to make a max nuber of cubes
    count = 0
    #Number of cubes in scene
    while count < 72:
        #function to add 72 cubes in scene at random
        new_cube = RandomCube()
        scene.add_object(new_cube)
        count += 1


    # Game loop, runs forever
    while True:

        # Process OS events
        for event in pygame.event.get():
            
            # Checks if the user closed the window
            if event.type == pygame.QUIT:
                # Exits the application immediately
                return
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    return
                axis.normalize() 
        # Clears the screen with a very dark blue (0, 0, 20)
        screen.fill((0, 0, 20))

        keys=pygame.key.get_pressed()
        # Confine the mouse to the center of the screen         
        pygame.mouse.set_pos(res_x/2, res_y/2)        

        # Get the mouse movement from the last frmae
        rel = pygame.mouse.get_rel()

        # Gets the rotation angle
        rotAngle = rel[0] * 4

        if rel[0] != 0:
            # Rotates the object, considering the time passed (not linked to frame rate)
            q = Quaternion.AngleAxis(axis, math.radians(rotAngle) * delta_time)
            
            #camera rotation
            scene.camera.rotation = q * scene.camera.rotation
    
        ''' Movement Stuff'''
        
        #going forwards
        if keys[pygame.K_w]:
            scene.camera.position += scene.camera.forward() * delta_time * 4
        #going backwards
        if keys[pygame.K_s]:
            scene.camera.position -= scene.camera.forward() * delta_time * 4
        #going left
        if keys[pygame.K_a]:
            scene.camera.position -= scene.camera.right() * delta_time * 4
        #going right
        if keys[pygame.K_d]:
            scene.camera.position += scene.camera.right() * delta_time * 4
            
        # Render scene
        scene.render(screen)

        # Swaps the back and front buffer, effectively displaying what we rendered
        pygame.display.flip()

        #Limit fps to 144
        while time.time() - prev_time < 0.00694:
            continue

        # Updates the timer, so we we know how long has it been since the last frame
        delta_time = time.time() - prev_time
        prev_time = time.time()
Ejemplo n.º 9
0
def main():
    # Initialize pygame, with the default parameters
    pygame.init()

    # Define the size/resolution of our window
    screenX = 640
    screenY = 480

    # Create a window and a display surface
    screen = pygame.display.set_mode((screenX, screenY))

    # Create a scene
    scene = Scene("TesteCena")
    scene.camera = Camera(False, screenX, screenY)

    # Moves the camera back 2 units
    scene.camera.position -= Vector3(0, 0, 2)

    # Create a sphere and place it in a scene, at position (0,0,0)
    obj = Object3d("Object")
    obj.scale = Vector3(1, 1, 1)
    obj.position = Vector3(0, 0, 0)

    #Number of sides of the cilinder
    sides = 12

    #Create a cilinder
    obj.mesh = Mesh.create_cylinder(sides, 1, 1, None)

    #Create a sphere
    #obj.mesh = Mesh.create_sphere((1, 1, 1), 12, 12)
    
    #Create a cube
    #obj.mesh = Mesh.create_cube((5, 5, 5))
    
    obj.material = Material(Color(1, 0, 0, 1), "Material1")
    scene.add_object(obj)

    # Timer
    delta_time = 0
    prev_time = time.time()

    pygame.mouse.set_visible(True)
    pygame.event.set_grab(False)

    # Game loop, runs forever
    while True:
         #Busca o evento
        events = pygame.event.get()
        key = pygame.key.get_pressed()
        ang = 20

        #Quando é carregada a tecla W
        if key[pygame.K_w]:
            movement = Vector3(0, 1, 0)
            movement.normalize()
            obj.position = obj.position + movement * delta_time

        #Quando é carregada a tecla S
        if key[pygame.K_s]:
            movement = Vector3(0, -1, 0)
            movement.normalize()
            obj.position = obj.position + movement * delta_time

        #Quando é carregada a tecla A
        if key[pygame.K_a]:
            movement = Vector3(-1, 0, 0)
            movement.normalize()
            obj.position = obj.position + movement * delta_time

        #Quando é carregada a tecla D
        if key[pygame.K_d]:
            movement = Vector3(1, 0, 0)
            movement.normalize()
            obj.position = obj.position + movement * delta_time

        #Quando é carregada a tecla Q
        if key[pygame.K_q]:
            movement = Vector3(0, 0, 1)
            movement.normalize()
            obj.position = obj.position + movement * delta_time

        #Quando é carregada a tecla E
        if key[pygame.K_e]:
            movement = Vector3(0, 0, -1)
            movement.normalize()
            obj.position = obj.position + movement * delta_time
        
        #Quando é carregada a seta para a direita
        if key[pygame.K_RIGHT]:
            rot = Vector3(0, -1, 0)
            q = Quaternion.AngleAxis(rot.normalized(), math.radians(ang) * delta_time)
            obj.rotation = q * obj.rotation

        #Quando é carregada a seta para a esquerda
        if key[pygame.K_LEFT]:
            rot = Vector3(0, 1, 0)
            q = Quaternion.AngleAxis(rot.normalized(), math.radians(ang) * delta_time)
            obj.rotation = q * obj.rotation
            
        #Quando é carregada a seta para baixo
        if key[pygame.K_DOWN]:
            rot = Vector3(-1, 0, 0)
            q = Quaternion.AngleAxis(rot.normalized(), math.radians(ang) * delta_time)
            obj.rotation = q * obj.rotation

        #Quando é carregada a seta para cima
        if key[pygame.K_UP]:
            rot = Vector3(1, 0, 0)
            q = Quaternion.AngleAxis(rot.normalized(), math.radians(ang) * delta_time)
            obj.rotation = q * obj.rotation

        #Quando é carregada a tecla PgUp
        if key[pygame.K_PAGEUP]:
            rot = Vector3(0, 0, 1)
            q = Quaternion.AngleAxis(rot.normalized(), math.radians(ang) * delta_time)
            obj.rotation = q * obj.rotation

        #Quando é carregada a tecla PgDn
        if key[pygame.K_PAGEDOWN]:
            rot = Vector3(0, 0, -1)
            q = Quaternion.AngleAxis(rot.normalized(), math.radians(ang) * delta_time)
            obj.rotation = q * obj.rotation

        for event in events:
            #Quando é carregada a tecla ESC
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    exit()
                    
            #Quando é carregado o botão para sair do programa
            if event.type == pygame.QUIT:
                exit()

        # Clears the screen with a very dark blue (0, 0, 20)
        screen.fill((0, 0, 0))

        scene.render(screen)

        # Swaps the back and front buffer, effectively displaying what we rendered
        pygame.display.flip()

        # Updates the timer, so we we know how long has it been since the last frame
        delta_time = time.time() - prev_time
        prev_time = time.time()
Ejemplo n.º 10
0
def main():
    """Main function, it implements the application loop"""
    # Initialize pygame, with the default parameters
    pygame.init()

    # Define the size/resolution of our window
    res_x = 1280
    res_y = 720

    # Create a window and a display surface
    screen = pygame.display.set_mode((res_x, res_y))

    # Create a scene
    scene = Scene("TestScene")
    scene.camera = Camera(False, res_x, res_y)

    # Moves the camera back 2 units
    scene.camera.position -= Vector3(0, 0, 4)
    scene.camera.rotation = Quaternion.AngleAxis(Vector3(1, 0, 0),
                                                 math.radians(-15))

    # Creates the terrain meshes and materials
    terrain_meshes, terrain_materials = create_terrain()

    # Create container object for all the terrain sub-objects
    master_object = Object3d("TerrainObject")
    master_object.position = Vector3(0, -1, 0)
    scene.add_object(master_object)

    # Create the terrain objects and place it in a scene, at position (0,0,0)
    for _, (mesh, material) in enumerate(zip(terrain_meshes,
                                             terrain_materials)):
        obj = Object3d("TerrainObject")
        obj.scale = Vector3(1, 1, 1)
        obj.position = Vector3(0, 0, 0)
        obj.mesh = mesh
        obj.material = material
        master_object.add_child(obj)

    # Specify the rotation of the object. It will rotate 15 degrees around the axis given,
    # every second
    angle = 15
    axis = Vector3(0, 1, 0)
    axis.normalize()

    # Timer
    delta_time = 0
    prev_time = time.time()

    # Show mouse cursor
    pygame.mouse.set_visible(True)
    # Don't lock the mouse cursor to the game window
    pygame.event.set_grab(False)

    # Game loop, runs forever
    while True:
        # Process OS events
        for event in pygame.event.get():
            # Checks if the user closed the window
            if event.type == pygame.QUIT:
                # Exits the application immediately
                return
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    return

        # Clears the screen with a very dark blue (0, 0, 20)
        screen.fill((0, 0, 0))

        # Rotates the object, considering the time passed (not linked to frame rate)
        q = Quaternion.AngleAxis(axis, math.radians(angle) * delta_time)
        master_object.rotation = q * master_object.rotation

        #Commented code serves to make benchmarks
        Mesh.stat_vertex_count = 0
        Mesh.stat_transform_time = 0
        Mesh.stat_render_time = 0

        scene.render(screen)

        #Writes the benchmarks results
        print("Frame stats:")
        print(f"Vertex count = {Mesh.stat_vertex_count}")
        print(f"Transform time = {Mesh.stat_transform_time}s")
        print(f"Render time = {Mesh.stat_render_time}s")

        # Swaps the back and front buffer, effectively displaying what we rendered
        pygame.display.flip()

        # Updates the timer, so we we know how long has it been since the last frame
        delta_time = time.time() - prev_time
        prev_time = time.time()

        print(f"Frame time = {delta_time}s")
def __Main():
    """
    Main app loop
    """
    # Pygame initialization
    pygame.init()
    pygame.freetype.init()
    pygame.display.set_caption("Breakout Breakdown Forever")

    window = pygame.display.set_mode(
        (HORIZONTAL_RESOLUTION, VERTICAL_RESOLUTION))

    # Cameras
    game_camera = Camera(False, HORIZONTAL_RESOLUTION, VERTICAL_RESOLUTION)
    menu_camera = Camera(True, HORIZONTAL_RESOLUTION, VERTICAL_RESOLUTION)

    # Tilt camera to desired view
    game_camera.position -= Vector3(0, 5, 20)
    angle = -15
    game_camera.rotation = Quaternion.AngleAxis(Vector3(1, 0, 0),
                                                math.radians(angle))

    game_scene.camera = game_camera
    menu_scene.camera = menu_camera

    # Correct paddle movement to match with mouse position on screen
    Paddle.V_RES = VERTICAL_RESOLUTION
    Paddle.H_RES = HORIZONTAL_RESOLUTION
    Paddle.CAMERA_CORRECTION = -game_camera.position.y + 7  #  mat angle of -15

    # Make and trigger level builder for the first stage
    level_builder = LevelBuilder("Level Builder")
    level_builder.make_level(game_scene)

    # Add it to the game scene
    game_scene.add_object(level_builder)

    # Create and add a menu object to the menu scene
    menu_scene.add_object(MainMenu("MENU"))

    # Fill the scene manager's scene list
    SceneManager.scene_list = []
    SceneManager.scene_list.append(menu_scene)
    SceneManager.scene_list.append(game_scene)

    # Set up delta time
    delta_time = 0
    prev_time = time.time()

    # Show mouse cursor
    pygame.mouse.set_visible(True)
    # Don't lock the mouse cursor to the game window
    pygame.event.set_grab(False)

    is_running = True

    SceneManager.switch_scene(0)
    # Main game loop
    while is_running:

        for event in pygame.event.get():
            # Checks if the user closed the window
            if event.type == pygame.QUIT:
                # Exits the application immediately
                is_running = False
            elif event.type == pygame.KEYDOWN:
                # If ESC is pressed exit the game
                if event.key == pygame.K_ESCAPE:
                    is_running = False

        __current_scene = SceneManager.current_scene
        # Update the Display
        window.fill(__current_scene.BACKGROUND_COLOR)
        __current_scene.update_objects(delta_time)
        __current_scene.render(window)

        pygame.display.flip()

        # Updates delta time, so we we know how long has it been since the last frame
        delta_time = time.time() - prev_time
        prev_time = time.time()
Ejemplo n.º 12
0
def main():
    """Main function, it implements the application loop"""
    # Initialize pygame, with the default parameters
    pygame.init()

    # Define the size/resolution of our window
    res_x = 640
    res_y = 480

    # Create a window and a display surface
    screen = pygame.display.set_mode((res_x, res_y))

    # Create a scene
    scene = Scene("TestScene")
    scene.camera = Camera(False, res_x, res_y)

    # Moves the camera back 2 units
    scene.camera.position = Vector3(0, 0, -2)

    # Create a cube and place it in a scene, at position (0,0,0)
    obj1 = Object3d("TestObject")
    obj1.scale = Vector3(1, 1, 1)
    obj1.position = Vector3(0, 0, 2)
    obj1.mesh = Mesh.create_cube((1, 1, 1))
    obj1.material = Material(Color(1, 0, 0, 1), "TestMaterial1")
    scene.add_object(obj1)

    # Create a second object, and add it as a child of the first object
    # When the first object rotates, this one will also mimic the transform
    obj2 = Object3d("ChildObject")
    obj2.position += Vector3(0, 0.75, 0)
    obj2.mesh = Mesh.create_cube((0.5, 0.5, 0.5))
    obj2.material = Material(Color(0, 1, 0, 1), "TestMaterial2")
    obj1.add_child(obj2)

    # Specify the rotation of the object. It will rotate 15 degrees around the axis given,
    # every second
    angle = 15
    axis = Vector3(1, 0.7, 0.2)
    axis.normalize()

    # Timer
    delta_time = 0
    prev_time = time.time()

    pygame.mouse.set_visible(False)
    pygame.event.set_grab(True)

    # Game loop, runs forever
    while True:
        # Process OS events
        for event in pygame.event.get():
            # Checks if the user closed the window
            if event.type == pygame.QUIT:
                # Exits the application immediately
                return
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    # If ESC is pressed exit the application
                    return

        # Clears the screen with a very dark blue (0, 0, 20)
        screen.fill((0, 0, 20))

        # Rotates the object, considering the time passed (not linked to frame rate)
        q = Quaternion.AngleAxis(axis, math.radians(angle) * delta_time)
        obj1.rotation = q * obj1.rotation

        scene.render(screen)

        # Swaps the back and front buffer, effectively displaying what we rendered
        pygame.display.flip()

        # Updates the timer, so we we know how long has it been since the last frame
        delta_time = time.time() - prev_time
        prev_time = time.time()
Ejemplo n.º 13
0
def main():

    # Initialize pygame, with the default parameters
    pygame.init()

    # Define the size/resolution of our window
    res_x = 1280
    res_y = 720

    # Create a window and a display surface
    screen = pygame.display.set_mode((res_x, res_y))

    # Create a scene
    scene = Scene("TestScene")
    scene.camera = Camera(False, res_x, res_y)

    # Moves the camera back 2 units
    scene.camera.position -= Vector3(0, 0, 0)

    # Creates the terrain meshes and materials
    terrain_object = create_terrain()
    scene.add_object(terrain_object)

    # Minimum time between player shots
    shot_cooldown = 0.2
    # Timer for the shot cooldown
    shot_timer = 0
    # Storage for all the shots active in the game
    shots = []

    # Timer
    delta_time = 0
    prev_time = time.time()

    # Don't show mouse cursor
    pygame.mouse.set_visible(False)
    # Lock the mouse cursor to the game window
    pygame.event.set_grab(True)

    # Game loop, runs forever
    while True:
        #Busca o evento
        events = pygame.event.get()
        key = pygame.key.get_pressed()
        speed = 0.05
        ang = 20

        #Manter o rato no centro do ecrã
        displayCenter = [screen.get_size()[i] // 2 for i in range(2)]
        mouseMove = (0, 0)
        pygame.mouse.set_pos(displayCenter)

        #Buscar o movimento do rato e devolve (x, y)
        mouseMove = pygame.mouse.get_rel()

        #Código para movimentação da câmara a partir do movimento do rato
        rot = Vector3(mouseMove[1], mouseMove[0], 0)
        scene.camera.rotation *= Quaternion.AngleAxis(
            rot,
            math.radians(ang) * delta_time)

        #Para impedir que a câmara rode no eixo do Z
        scene.camera.rotation.z = 0

        #Quando é carregada a tecla W
        if key[pygame.K_w]:
            movement = Vector3(0, 0, 1)
            movement.normalize()
            scene.camera.position += movement * delta_time + scene.camera.forward(
            ) * speed

        #Quando é carregada a tecla S
        if key[pygame.K_s]:
            movement = Vector3(0, 0, -1)
            movement.normalize()
            scene.camera.position += movement * delta_time - scene.camera.forward(
            ) * speed

        #Quando é carregada a tecla A
        if key[pygame.K_a]:
            movement = Vector3(-1, 0, 0)
            movement.normalize()
            scene.camera.position += movement * delta_time - scene.camera.right(
            ) * speed

        #Quando é carregada a tecla D
        if key[pygame.K_d]:
            movement = Vector3(1, 0, 0)
            movement.normalize()
            scene.camera.position += movement * delta_time + scene.camera.right(
            ) * speed

        # Process OS events
        for event in events:
            # Checks if the user closed the window
            if event.type == pygame.QUIT:
                # Exits the application immediately
                return
            elif event.type == pygame.KEYDOWN:
                # If ESC is pressed exit the application
                if event.key == pygame.K_ESCAPE:
                    return
            elif event.type == pygame.MOUSEBUTTONDOWN:
                # If the user has the mouse button down
                if shot_timer <= 0:
                    # We're not on cooldown, so we can shoot

                    # Get the mouse position and convert it to NDC (normalized
                    # device coordinates)
                    mouse_pos = pygame.mouse.get_pos()
                    mouse_pos = ((mouse_pos[0] / res_x) * 2 - 1,
                                 (mouse_pos[1] / res_y) * 2 - 1)

                    # Create a shot
                    shot = Shot()
                    # Initialize the position and direction of the shot, based on the
                    # mouse position on the screen. For this, we request the scene camera the
                    # ray corresponding to the mouse position
                    shot.position, shot.direction = scene.camera.ray_from_ndc(
                        mouse_pos)

                    # Add the shot to the scene (for rendering) and on the shot storage, for
                    # all other operations
                    scene.add_object(shot)
                    shots.append(shot)

                    # Reset the cooldown
                    shot_timer = shot_cooldown

        # Clears the screen with a black (0, 0, 0)
        screen.fill((0, 0, 0))

        # Animate shots
        # We need the following to keep track of all shots we'll have to destroy,
        # since we can't change the storage while we're iterating it
        shots_to_destroy = []
        for shot in shots:
            # Update the shot
            shot.update(delta_time)

            # Check if the shot is too far away, and add it to the destruction list,
            # besides removing it from the scene
            if shot.position.z > 12:
                # Destroy shot
                shots_to_destroy.append(shot)
                scene.remove_object(shot)

        # Update shot cooldown
        shot_timer -= delta_time

        # Actually delete objects
        shots = [x for x in shots if x not in shots_to_destroy]

        # Render scene
        scene.render(screen)

        # Swaps the back and front buffer, effectively displaying what we rendered
        pygame.display.flip()

        # Updates the timer, so we we know how long has it been since the last frame
        delta_time = time.time() - prev_time
        prev_time = time.time()