Created
February 16, 2020 13:44
-
-
Save inclement/bb08b2e1406d62b314f15ed40e60c0b8 to your computer and use it in GitHub Desktop.
Demonstration of having drawing wrap around the sceen in Kivy.
This file contains 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
from kivy.app import App | |
from kivy.graphics import Ellipse, InstructionGroup, Color, Translate, Canvas, PushMatrix, PopMatrix | |
from kivy.uix.widget import Widget | |
from kivy.clock import Clock | |
import math | |
import itertools | |
import random | |
class TestApp(App): | |
def build(self): | |
return WrappedDrawingWidget() | |
class MovingObject(): | |
def __init__(self, colour): | |
self.angle = 0 | |
self.colour = Color(*colour) | |
self.ellipse = Ellipse(0, 0, 100, 100) | |
self.angle = random.random() * 2 * math.pi | |
self.velocity = 100 | |
def update(self, dt, size): | |
x, y = self.ellipse.pos | |
self.ellipse.pos = x + self.velocity * math.cos(self.angle) * dt, y + self.velocity * math.sin(self.angle) * dt | |
size_x, size_y = size | |
el_x, el_y = self.ellipse.pos | |
if el_x > size_x: | |
self.ellipse.pos = [el_x - size_x, el_y] | |
elif el_x < -100: | |
self.ellipse.pos = [el_x + size_x, el_y] | |
if el_y > size_y: | |
self.ellipse.pos = [el_x, el_y - size_y] | |
elif el_y < -100: | |
self.ellipse.pos = [el_x, el_y + size_y] | |
self.angle += random.random() * 0.5 * dt | |
def reset(self): | |
self.ellipse.pos = [0, 0] | |
class WrappedDrawingWidget(Widget): | |
def __init__(self, **kwargs): | |
super().__init__(**kwargs) | |
with self.canvas: | |
self.wrapped_drawing_layer = Canvas() | |
self.setup_canvas() | |
Clock.schedule_interval(self.update, 0) | |
def setup_canvas(self): | |
self.objects = [] | |
with self.wrapped_drawing_layer: | |
for _ in range(3): | |
self.objects.append(MovingObject([random.random() for _ in range(3)])) | |
self.translations = [] | |
for x in (-1, 0, 1): | |
for y in (-1, 0, 1): | |
t = Translate() | |
self.canvas.add(PushMatrix()) | |
self.canvas.add(t) | |
self.translations.append(t) | |
self.canvas.add(self.wrapped_drawing_layer) | |
self.canvas.add(PopMatrix()) | |
self.on_size(self, self.size) | |
def on_size(self, instance, size): | |
for obj in self.objects: | |
obj.reset() | |
for i, (dx, dy) in enumerate(itertools.product((-1, 0, 1), (-1, 0, 1))): | |
self.translations[i].xy = (dx * self.width, dy * self.height) | |
print("translation xy is", self.translations[i].xy) | |
def update(self, dt): | |
for obj in self.objects: | |
obj.update(dt, self.size) | |
TestApp().run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment