Created
May 30, 2020 11:59
-
-
Save shorinji/e1ee71055263ca5d4b179b961f058564 to your computer and use it in GitHub Desktop.
example of smooth moving over a grid in pygame
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import pygame | |
import math | |
from pygame.locals import * | |
TILE_SIZE = 32 | |
WIDTH = 32 * 20 | |
HEIGHT = 32 * 10 | |
BLACK = Color(0, 0, 0) | |
BLUE = Color(0, 0, 200) | |
playerLocation = [10, 5] | |
pygame.init() | |
screen = pygame.display.set_mode([WIDTH, HEIGHT]) | |
offset = 0.0 | |
IS_MOVING = False | |
MOVE_SPEED = 1 | |
while 1: | |
for event in pygame.event.get(): | |
if event.type == pygame.QUIT: | |
sys.exit() | |
if event.type == pygame.KEYDOWN and not IS_MOVING: | |
if event.key == K_ESCAPE: | |
sys.exit() | |
elif event.key == K_LEFT: | |
IS_MOVING = True | |
currentMovePosition = [playerLocation[0] * TILE_SIZE, playerLocation[1] * TILE_SIZE] | |
targetMovePosition = [(playerLocation[0] - 1) * TILE_SIZE, playerLocation[1] * TILE_SIZE] | |
moveIncrement = [MOVE_SPEED * -1, 0] | |
elif event.key == K_RIGHT: | |
IS_MOVING = True | |
currentMovePosition = [playerLocation[0] * TILE_SIZE, playerLocation[1] * TILE_SIZE] | |
targetMovePosition = [(playerLocation[0] + 1) * TILE_SIZE, playerLocation[1] * TILE_SIZE] | |
moveIncrement = [MOVE_SPEED, 0] | |
elif event.key == K_DOWN: | |
IS_MOVING = True | |
currentMovePosition = [playerLocation[0] * TILE_SIZE, playerLocation[1] * TILE_SIZE] | |
targetMovePosition = [playerLocation[0] * TILE_SIZE, (playerLocation[1] + 1) * TILE_SIZE] | |
moveIncrement = [0, MOVE_SPEED] | |
elif event.key == K_UP: | |
IS_MOVING = True | |
currentMovePosition = [playerLocation[0] * TILE_SIZE, playerLocation[1] * TILE_SIZE] | |
targetMovePosition = [playerLocation[0] * TILE_SIZE, (playerLocation[1] - 1) * TILE_SIZE] | |
moveIncrement = [0, MOVE_SPEED * -1] | |
if IS_MOVING: | |
currentMovePosition[0] += moveIncrement[0] | |
currentMovePosition[1] += moveIncrement[1] | |
if currentMovePosition[0] == targetMovePosition[0] and currentMovePosition[1] == targetMovePosition[1]: | |
IS_MOVING = False | |
playerLocation[0] = targetMovePosition[0] / TILE_SIZE | |
playerLocation[1] = targetMovePosition[1] / TILE_SIZE | |
playerPos = Rect(currentMovePosition[0], currentMovePosition[1], TILE_SIZE, TILE_SIZE) | |
else: | |
playerPos = Rect(playerLocation[0] * TILE_SIZE, playerLocation[1] * TILE_SIZE, TILE_SIZE, TILE_SIZE) | |
screen.fill(BLACK) | |
pygame.draw.rect(screen, BLUE, playerPos) | |
pygame.display.flip() | |
pygame.time.wait(10) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment