VPython键盘和鼠标移动操作

作者 : magang    标签: vpython
切换行号 全选 下载代码

在张老师代码的基础上,补充了鼠标的操作部分,不是很准确。

本来想发到原帖的回复中,结果格式乱了,先放在这里了。

01from visual import *
02  
03box(color=color.red)
04arrow(pos=(0,.5,0), axis=(0,1,0), color=color.green)
05arrow(pos=(.5,0,0), axis=(1,0,0), color=color.cyan)
06  
07scene.autoscale = False
08scene.autocenter = False
09scene.range = 2
10 
11def drag_plane():
12    "返回鼠标射线与X-Y平面的交点"
13    return scene.mouse.project(normal=(0,0,1), point=(0,0,0))
14 
15pick = None # 当前鼠标选中的点
16 
17while True:
18    rate(50)
19    if scene.kb.keys:
20        s = scene.kb.getkey()
21        dictx = norm(cross(scene.forward, scene.up))
22        dicty = -norm(scene.up)
23        if s == "left" or s == "a":
24            scene.center += 0.1 * dictx
25        elif s == "right" or s == "d":
26            scene.center -= 0.1 * dictx
27        elif s == "up" or s == "w":
28            scene.center += 0.1 * dicty
29        elif s == "down" or s == "s":
30            scene.center -= 0.1 * dicty
31        else:
32            print dictx
33            print dicty
34            print scene.range
35 
36    if scene.mouse.events:
37        m1 = scene.mouse.getevent()
38        if m1.drag:
39            drag_pos = drag_plane()
40            pick = 'draged point'
41        elif m1.drop:
42            pick = None
43 
44    if pick:
45        # 获得当前鼠标投射到与X-Y平面上的坐标
46        new_pos = drag_plane()
47        if new_pos != drag_pos: # 如果鼠标移动了
48            # 更改屏幕中心的位置,0.5是移动速度
49            scene.center += -(new_pos - drag_pos)*0.5
50            drag_pos = new_pos # 更新拖动的起始位置

loading...