Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Keyboard Controller (PC-Like)

edited March 2016 in Code Sharing Posts: 79

This is an example program that uses the keyboard's input to control a player on the screen. This works best when using a Bluetooth keyboard. There's probably a better way of executing this, but for now, you have to hit the keys repetitively. Here's the code:

function setup()
    print("Use W, A, S, and D to move and X to open the chest.")
    showKeyboard()
    player=sprite("Planet Cute:Character Boy")
    chest=sprite("Planet Cute:Chest Closed")
    px=100
    py=HEIGHT-100
    points=0
    parameter.watch("points")
    chestClosed=true
end

function draw()
    background(95, 70, 31, 255)
    if chestClosed then chest=sprite("Planet Cute:Chest Closed", WIDTH/2, HEIGHT/2) end
    player=sprite("Planet Cute:Character Boy", px, py)
    showKeyboard()
end

function keyboard(key)
    if (key == "w" or key == "W") then
        py = py + 10 
    end
    if (key == "a" or key == "A") then
        px = px - 10 
    end
    if (key == "s" or key == "S") then
        py = py - 10 
    end
    if (key == "d" or key == "D") then
        px = px + 10 
    end
    if (key == "x" or key == "X") then
        if touchingChest() then
            chestClosed=false
            sound(SOUND_PICKUP, 24870)
            points = points + 10 
        end
    end
end

function touchingChest()
    if (px < WIDTH/2+50 and
        px > WIDTH/2-50 and
        py < HEIGHT/2+85 and
        py > HEIGHT/2-85) then return true
    else
        return false
    end
end

Comments

  • IgnatzIgnatz Mod
    Posts: 5,396

    @niorg2606 - I would load the images just once at the start

    player=readImage("Planet Cute:Character Boy")
    

    And this is how to sprite them

    sprite(player, px, py)
    

    Additionally, there's no need to test for both upper and lower case, just do this

    if string.lower(key)=="w" then
    
  • Posts: 79

    Additionally, there's no need to test for both upper and lower case, just do this

    if string.lower(key)=="w" then

    When I tested the program with a BT Keyboard, It didn't register the keystroke when I had caps lock on.

  • So is there a way to check if a key is still being pressed and I love my Logitech keyboard. Though it was quite expensive and doesn't fit my new iPad.

  • @SaladFingers I'm pretty sure the keyboard is only called when the key is pushed down, and does not detect when it is released. I asked that quite a while ago. Still, you can make quite fun games based off the keyboard.

  • edited October 2016 Posts: 12

    Yeah, thanks. I'm curious, what kind of keyboard do you use?

  • @SaladFingers a Belkin, it's part of my case.

Sign In or Register to comment.