Trying to get a rectangle to move around the screen with the arrow keys

edited August 2017 in Python Mode

Ok, I am using the KeyCoded method to get a rectangle to move around the screen. I know the challenges of it already, I am just trying to figure out a way around it.

1) Since the Draw Function continues to run, I am pressing the LEFT arrow and the rectangle runs off the screen leaving a ghosting trail behind it. So instead I am going to use KeyRelease(): so that it doesn`t continually move once the key is not being pressed.

2) The trail is because I am not clearing the screen or changing the background to white after each key press - but what if I am making a game and there are other objects on the screen, I don`t want them to disappear each time the key is pressed. How can I get around this.

x1=100
x2=25
y1=0
y2=25

def setup():
    size(200, 200)
    background(255) # white


def draw():
    global x1,y1,x2,y2
    fill(155)
    rect(x1, y1, x2, y2)

def keyReleased():
    global x1, y1, x2, y2
    rect(x1, y1, x2, y2)
    if (key==CODED):
        if (keyCode == LEFT):
            x1=x1-10
            rect(x1, y1, x2, y2)
        elif (keyCode== RIGHT):
            x1=x1+10
            rect(x1,y1,x2,y2)
        elif (keyCode== UP):
            y1=y1-10
            rect(x1,y1,x2,y2)
        elif (keyCode== DOWN):
            y1=y1+10
            rect(x1,y1,x2,y2)
Tagged:

Answers

  • Answer ✓

    KeyReleased() might or might not work for you. Sometimes it is bettwer to use keyPressed as it executes the command while the key is pressed. If you use key released, you only get the command each time the key is released. In a game, I can envision presseng the key to go right and stop pressing it to stop moving. It really depends on your game and on the final feel and you should explore both. Implementing either should be easy... keep in mind that if you are in a mac, the keypressed behavior might behave differently... based on what I have read here in the forum.

    I don`t want them to disappear each time the key is pressed. How can I get around this.

    You render all the elements in the scene each time. Or you can draw your game in a second buffer and you draw this buffer first follwed by rectangle. This method is efficient as you don't have to render the background of your game each time. This only works if your background doesn't change. Rendering the whole scene seems to be a common concept. It seems expensive but it works in many applications. Only in special cases you want to work with alternative solutions.

    Lastly, to avoid the trail left by the rectangle, yes... call background(0); as your first line of draw().

    Kf

Sign In or Register to comment.