Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Tk_3DcubeXspin.py
- # drag-to-rotate
- import math,time,os,sys
- from Tkinter import *
- from PIL import ImageTk, Image
- w=640
- h=640
- Size = 10
- class Cv():
- x,y,z=0,0,0
- xx,yy=0,0
- objv=False
- ANGLEX = 0
- ANGLEY = 0
- ANGLEZ = 0
- PX = 0
- PY = 0
- PZ = 200
- xm,ym,x2,y2 = 3,2,0,0
- rx=1
- ry=1
- run=1
- cv=Cv()
- halfResX = w/2
- halfResY = h/2
- def click(event):
- cv.xx,cv.yy = (event.x,event.y)
- def drag(event):
- tx = (event.x-cv.xx)
- ty = (event.y-cv.yy)
- cv.xm += tx
- cv.ym += ty
- cv.xm %= 360
- cv.ym %= 360
- cv.xx,cv.yy = (event.x,event.y)
- root = Tk()
- canvas = Canvas(root,width=w,height=h)
- canvas.pack()
- canvas.bind('<Button-1>',click)
- canvas.bind('<B1-Motion>',drag)
- distance = 400 # object size to create distance illusion
- xyz=80
- VX = [-xyz, -xyz, -xyz, -xyz, xyz, xyz, xyz, xyz]
- VY = [-xyz, xyz, -xyz, xyz, -xyz, xyz, -xyz, xyz]
- VZ = [-xyz, -xyz, xyz, xyz, -xyz, -xyz, xyz, xyz]
- faces = [(0,1,3,2),(7,5,4,6),(0,2,6,4),(7,3,1,5),(7,3,2,6),(0,1,5,4)]
- colors = 'red darkorange yellow green blue purple'.split()
- def animate():
- while cv.run:
- rax = cv.ANGLEX*math.pi/180
- ray = cv.ANGLEY*math.pi/180
- sinx = math.sin(rax)
- cosx = math.cos(rax)
- siny = math.sin(ray)
- cosy = math.cos(ray)
- r1 = []
- r2 = []
- for n in range(8):
- YX = VX[n]*cosy - VZ[n]*siny - VX[n]
- YZ = VX[n]*siny + VZ[n]*cosy - VZ[n]
- XY = VY[n]*cosx - (VZ[n]+YZ)*sinx - VY[n]
- XZ = VY[n]*sinx + (VZ[n]+YZ)*cosx - (VZ[n]+YZ)
- XR = YX
- YR = XY
- ZR = XZ+YZ
- z = (VZ[n]+cv.PZ+ZR)/distance
- x = ((VX[n]+cv.PX+XR)/z)+halfResX
- y = ((VY[n]+cv.PY+YR)/z)+halfResY
- r1.append([x,y])
- r2.append(z)
- canvas.delete('all')
- t = []
- c = 0
- for f in faces:
- z1 = [r1[z] for z in f]
- z2 = [r2[z] for z in f]
- t.append([max(z2),z1,colors[c]])
- c += 1
- z = False
- if time.time() % 0.9 > 0.45: z = True
- t.sort(reverse=z)
- for c,a,b in t:
- canvas.create_polygon(a,fill=b)
- cv.ANGLEX = cv.ym
- cv.ANGLEY = cv.xm
- canvas.create_text((30,20),text='Drag Mouse To Rotate Cube',anchor=W)
- canvas.create_text((30,40),text='X: %d'%(cv.xm),anchor=W)
- canvas.create_text((30,60),text='Y: %d'%(cv.ym),anchor=W)
- break
- root.after(60, animate)
- animate()
- root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement