How to move an object using keyboard.

200 views
Skip to first unread message

Juanjo Marín

unread,
Jul 24, 2016, 11:38:22 AM7/24/16
to Glowscript Users
Hello. My name is Juanjo, I am from Majorca (Spain) and I find GlowScript VPython really useful when teaching Physics and Computational Science.

The problem  have is: How to handle keyboard with GlowScript. I have read information and examples in 'help' section but, I am unable to fully understand it.

i.e.:

How is the code for moving a rectangle (plane) with the arrows keys?? (any other keys are also welcome).

Thanks for your help!

Best regards.
Juanjo.

Aaron Titus

unread,
Jul 24, 2016, 12:06:32 PM7/24/16
to glowscri...@googlegroups.com
Hi Jaunjo,

My “Physics for Video Games” course uses keyboard interactions. The chapter that introduces this topic is posted at:


A simple example is at:


A second example is at:



You will need code similar to this:

def keyboard(event):
    if event.type=='keydown':
        k = event.which
#        print(k)
        if k == 39:
            shooter.v=2*vector(1,0,0)
        elif k == 37:
            shooter.v=2*vector(-1,0,0)
        elif k == 65:
            shooter.v=4*vector(-1,0,0)
        elif k == 83:
            shooter.v=4*vector(1,0,0)
        elif k==32:
            bullet=sphere(pos=shooter.pos, radius=0.1, color=color.white)
            bullet.v=3*vector(0,1,0)
            bulletsList.append(bullet)
        else:
            shooter.v=vector(0,0,0)
       
scene.bind('keydown', keyboard) 

The scene.bind command connects an event (like keydown) to a function (mine was called keyboard). Then, in that function, you write code for different events and keys. Use a print statement to figure out the integer for a particular key.

Aaron


--

---
You received this message because you are subscribed to the Google Groups "Glowscript Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to glowscript-use...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Bruce Sherwood

unread,
Jul 24, 2016, 12:12:14 PM7/24/16
to Glowscript Users

Otro ejemplo -- Aquí un programa que muestra el nombre de la tecla:

 

box()

 

def keyInput(evt):

    s = evt.key

    print('['+s+']')

 

scene.bind('keydown', keyInput)

 

Usando este programa, se ve que los nombres de las teclas con flechas son “left”, “right”, “up”, y “down”, así que se puede mover la caja con este programa:

 

b = box()

 

def keyInput(evt):

    s = evt.key

    if s == 'left':

        b.pos.x = b.pos.x - 1

    elif s == 'right':

        b.pos.x = b.pos.x + 1

    elif s == 'down':

        b.pos.y = b.pos.y - 1

    elif s == 'up':

        b.pos.y = b.pos.y + 1

 

scene.bind('keydown', keyInput)

Reply all
Reply to author
Forward
0 new messages