Issues with smooth 2D movement in python

That’s a very old sketch of mine. :innocent:

BtW, I did a followup w/ 2 players instead of 1 both for Java Mode & p5js flavors: :sunglasses:

And now I’ve decided to do a Python Mode version as well. Check it out: :snake:

#!/bin/python2

"""
Players Movement (v1.1.0)
by GoToLoop (2020/Mar/11)

Discourse.Processing.org/t/issues-with-smooth-2d-movement-in-python/18556/4

GoToLoop.Trinket.io/sites/players-movement
Trinket.io/processing/62fab051ed

Reddit.com/r/processing/comments/bshqa8/
how_would_i_make_a_keypressed_function_support/eor5epo/

OpenProcessing.org/sketch/718355
OpenProcessing.org/sketch/717760

Studio.ProcessingTogether.com/sp/pad/export/ro.91tcpPtI9LrXp
"""

original_set = set # Save Python's builtin set() before Processing's import

from processing import *

ONLINE = '__papplet__' not in globals()

W = 750 if ONLINE else 1200
H = 450 if ONLINE else 600

PLAYERS = 2 # Number of players
BG = 0xff00FFFF # Cyan background

DIAMS = 50, 40 # Diameters
SPDS = 4, 5 # Speeds
INKS = 0xff0000FF, 0xffFF0000 # Blue, Red

KEYS = (
    tuple(ord(k) for k in 'WSAD'), # Player 1's keys
    (UP, DOWN, LEFT, RIGHT)) # Player 2's keys

players = PLAYERS * [ None ]
keysDown = original_set()

def setup():
    size(W, H)

    stroke(Player.OUTLINE)
    strokeWeight(Player.BOLD)
    ellipseMode(Player.MODE)

    for i in range(PLAYERS):
        d = DIAMS[i]
        dd = d << i
        players[i] = Player(dd, dd, d, SPDS[i], INKS[i], KEYS[i])


def draw():
    background(BG)
    for p in players: p.move().display()


def keyPressed(): keysDown.add(keyCode)

def keyReleased(): keysDown.discard(keyCode)


class Player:
    OUTLINE, BOLD, MODE = 0, 2, CENTER
    UP, DOWN, LEFT, RIGHT = range(4)

    def __init__(p, x, y, d, v, ink, keys):
        p.x = x
        p.y = y
        p.d = d
        p.v = v
        p.ink = color(ink)
        p.keys = keys


    def display(p):
        fill(p.ink)
        ellipse(p.x, p.y, p.d, p.d)
        return p


    def move(p):
        r = p.d >> 1
        v = p.v
        k = p.keys

        hor = (k[p.RIGHT] in keysDown) - (k[p.LEFT] in keysDown)
        ver = (k[p.DOWN]  in keysDown) - (k[p.UP]   in keysDown)

        p.x = constrain(p.x + v*hor, r, width  - r)
        p.y = constrain(p.y + v*ver, r, height - r)

        return p



ONLINE and run()
3 Likes