Login | Register

Input textbox

July 2, 2006, 14:18 by Calle
[loading]
-->
Often you need to have information from the user, and while the get_string function is not always very good or professional you might want to use an input box. This article will show you how to create one, working like the ones you see at internet everyday. You type, and when you reach the right side of the box it keeps scrolling the text to the left.

<b>This is a rewrite of the original article since some had a problem with implementing the earlier code. This is easier and it includes an example.</b>

I will start to just present the code. Note that the code is compatible with multiple textboxes; you can have an infintive number of the object in your room.

Create Event:
execute code:

selected = false;
mytext = "";

Mouse Event for Left Released:
execute code:

selected = true;

Mouse Event for Glob Left Pressed:
execute code:

selected = false;

Draw Event:
execute code:

//Set the font... destroy this if you want to use the code in your game
draw_set_font(font0);

draw_sprite(sprite_index,0,x,y);
draw_text(10,10,"Select a certain textbox by left mouse click";);
if (selected==true) {
mytext += keyboard_string;
keyboard_string="";
}

dl = mytext;
while(string_width(dl)>sprite_width-20){
dl = string_copy(dl,2,1000);
}

draw_text(x+10,y+sprite_height/2-string_height("A";)/2+2,
dl);

Key Release Event for <Backspace> Key:
execute code:

if (selected = true) {
mytext = string_copy(mytext,1,string_length(mytext)-1);
}


Okey, what do I do? First of all you should notice that all the variables that I initialize in the create event are local. That's why this will work with multiple instances. Then you can see how a textbox gets selected when it is hit with a mouse click. It is basically only a variable to is assigned the value of true (1). This wouldn't have any effect at all unless I wrap all the other coding with if (selected==true) ... that is very important.

The tricky part however is with a textbox that you don't know when to scroll the text or for how many characters. This is done in the draw event. I guess there are ways to calculate how many character must be deleted such that the text is not too long, but I chose to let the program guess. That is what the while loop does, it just delete one letter at the time until the text is not wider than it should be.

I will write no more about this, but you can study the code yourself. Ask if there is anything you want to know.

<b>The example is here: </b>http://gmtutorials.com/files/textboxexample.gm6

Comments

Loading comments... [loading]
.
Users logged in:

game maker articles, game maker examples, game maker tutorials, gmtutorials, game maker questions and answers, game maker crash course, how to create games