KeyUp and KeyDown events - events

I'm working on a typing program to learn touch typing and increase speed.
The program generates random words in the textbox (txtsrc) and the user must type the word in another textbox(txtinput) everything is going right until I stuck in this problem: I want to compare every char in txtinput when the user hit the key down if the key is correct to keep going if not change the color of char in txtsrc to red.
how can I allow the user to use the backspace to remove his errs
and how to compare the chars while the user input the text
I can't find the right algorithm please help
private void txtinput_KeyUp(object sender, KeyEventArgs e)
{
if (keycount < 0) { keycount++; }
if (e.KeyCode == Keys.Back)
{
--keycount;
txtsrc.Select(keycount, 1);
txtsrc.SelectionColor = Color.Black;
}
if (keycount >= 0 && txtinput.Text.Length > 0)
if (txtsrc.Text[keycount] != txtinput.Text[txtinput.Text.Length - 1])
{
txtsrc.Select(keycount, 1);
txtsrc.SelectionColor = Color.Red;
}
if (e.KeyCode != Keys.Back)
{
keycount++;
label1.Text = "Keycount: " + keycount.ToString();
}
}

Related

how to use GetAxisRaw with 2d movement (beginner unity)

I am making a platformer game where you have to dodge spikes, and I tried to use the transform.position method, but it gave too many bugs. With rigidbodies(rb.addforce), it has acceleration, and I saw somewhere that you could use getaxisraw to do it. Is there any way that I could add this to my current script without deviating too much (still being able to use wasd and arrow keys)?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerscript : MonoBehaviour
{
public float movespeed = 0.01f;
public Rigidbody2D rb;
public bool isgrounded = true;
public float jumpheight = 500f;
public float level = 1;
// Start is called before the first frame update
void Start()
{
rb = this.gameObject.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void FixedUpdate()
{
if (Input.GetKey(KeyCode.A) || (Input.GetKey(KeyCode.LeftArrow)))
{
rb.AddForce(-Vector2.right * movespeed);
}
if (Input.GetKey(KeyCode.W) && isgrounded || (Input.GetKey(KeyCode.UpArrow) && isgrounded))
{
rb.AddForce(transform.up * jumpheight);
isgrounded = false;
}
if (Input.GetKey(KeyCode.D)||(Input.GetKey(KeyCode.RightArrow)))
{
rb.AddForce(Vector2.right * movespeed);
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "enemy")
{
Debug.Log("hio");
if (level == 1)
{
Debug.Log("resetpos");
transform.position = new Vector3((float)-11.343, (float)-0.49, 0);
}
}
}
private void OnCollisionStay2D(Collision2D collision)
{
if (collision.gameObject.tag == "ground")
{
isgrounded = true;
}
}
}
From https://docs.unity3d.com/ScriptReference/Input.GetAxisRaw.html, I think that Input.GetAxisRaw("Horizontal") will return -1 if the user presses in left or a, 0 if the user is not pressing left or right or a or d, and 1 if the user presses right or d. Similarly, this also occurs for Input.GetAxisRaw("Vertical"). I think it will return -1 if the user wants to go down, 0 if the user is not pressing up or down, and 1 if the user wants to go up.
In FixedUpdate(), you can get Input.GetAxisRaw("Horizontal") to get whether they want to move right or left, and Input.GetAxisRaw("Vertical") to get whether they want to move down or up. Then, you can handle it by moving the character appropriately.
For example, you can do this:
void FixedUpdate()
{
if (Input.GetAxisRaw("Horizontal") == -1)
{
// Code to move left
}
else if (Input.GetAxisRaw("Horizontal") == 1) {
// Code to move right
}
if (Input.GetAxisRaw("Vertical") == -1)
{
// Code to move down or squat
}
else if (Input.GetAxisRaw("Vertical") == 1)
{
// Code to move up or jump
}
}
Please excuse me if I made any C# syntax errors.

How to specify allowed characters in keyboard?

I want to create a page for pin entry for both, android and iOS platforms. Numeric specification in Keyboard property is close to my needs. I can do something like this to restrict allowed characters and overall length. However I need to get rid of the dot character on the keyboard. How can I achieve that?
You can remove the dot from the soft keyboard.
Using the solution you linked and Keyboard="Numeric", you can use the same TextChanged event that restricts entry text size to restrict the '.'.
Example:
public void OnTextChanged(object sender, TextChangedEventArgs args)
{
var e = sender as Entry;
string val = e.Text;
if (string.IsNullOrEmpty(val))
{
return;
}
if (MaxLength > 0 && val.Length > MaxLength)
{
val = val.Remove(val.Length - 1);
}
if (val.Contains("."))
{
val.Replace(".", string.Empty);
}
e.Text = val;
}
Other option would be creating a Grid for the PIN. And show the PIN in a Label instead of and Entry to avoid pasting.

How Processing knows that user is pressing multiple key at the same time?

I have no idea how Processing knows that a user is pressing Ctrl and some character at the same time.
Multiple buttons at same time only. Is it possible?
ex: (Ctrl+r).
You have to first check if Ctrl has been pressed. If it has been pressed then you save a boolean as true. The next time you press a button you check if the button is the button you want (i.e. 'r') and if the boolean is true. If both are true then Processing knows...
Here's a demonstration:
boolean isCtrlPressed = false;
boolean isRPressed = false;
void draw() {
background(0);
fill(255);
if (isCtrlPressed) background(255, 0, 0);
if (isRPressed) background(0, 255, 0);
if (isCtrlPressed && isRPressed) background(255, 255, 0);
}
void keyPressed() {
if (keyCode == CONTROL && isCtrlPressed == false) isCtrlPressed = true;
if (char(keyCode) == 'R') isRPressed = true;
}
void keyReleased() {
if (keyCode == CONTROL) isCtrlPressed = false;
if (char(keyCode) == 'R') isRPressed = false;
}
I know this is a very old feed, but I have something that might help everyone with multiple key presses. This is for Processing's Python Mode, but I'm sure it can be implemented in some way for other modes.
import string
#string.printable is a pre-made string of all printable characters (you can make your own)
keys = {}
for c in string.printable:
#set each key to False in the keys dictionary
keys[c] = False
def keyPressed():
#If key is pressed, set key in keys to True
keys[key] = True
def keyReleased():
#If key is released, set key in keys to False
keys[key] = False
And then using multiple if statements, you can check the dictionary for whether the key is pressed or not.
if keys['w'] == True:
#Do something
if keys['s'] == True:
#Do something
if keys['a'] == True:
#Do something
if keys['d'] == True:
#Do something
if keys[' '] == True:
#Do something
And so on.
Hope this helps!
You could also override the keyPressed(KeyEvent) method and use the KeyEvent.isControlDown() method:
void keyPressed(KeyEvent ke) {
println(ke.isControlDown());
}
void draw(){
//need draw() method for keyPressed() to work
}
you can find out the "key" codes of any combination of "ctrl + *" or "Shift + *" by typing, but this method is not suitable for multi-clicking to control the game.
combination search code
void setup()
{
textAlign(CENTER,CENTER);
}
void draw()
{
background(0);
text(int(key),50,50);
}

How could I choose one particular file to load with loadStrings

The title is explicit enough, I want to let the user choose the text file he want to open.
I do not know if there is an explorer or an input field already implemented on processing.
Any help would be great.
Use selectInput. From the Processing reference:
Opens a platform-specific file chooser dialog to select a file for input. After the selection is made, the selected File will be passed to the 'callback' function. If the dialog is closed or canceled, null will be sent to the function, so that the program is not waiting for additional input. The callback is necessary because of how threading works.
I've modified the example sketch they provide in the reference to include loading the file with the loadStrings method.
String[] txtFile;
void setup() {
selectInput("Select a file to process:", "fileSelected");
}
void fileSelected(File selection) {
if (selection == null) {
println("Window was closed or the user hit cancel.");
} else {
String filepath = selection.getAbsolutePath();
println("User selected " + filepath);
// load file here
txtFile = loadStrings(filepath);
}
}
There is no Implemented method, but you could could make a buffer and monitor key presses like so:
String[] File;
String keybuffer = "";
Char TriggerKey = Something;
void setup(){
//do whatever here
}
void draw(){
//Optional, to show the current buffer
background(255);
text(keybuffer,100,100);
}
void keyPressed(){
if(keyCode >= 'a' && keyCode <= 'z'){
keybuffer = keybuffer + key;
}
if(key == TriggerKey){
File = loadStrings(keybuffer + ".txt");
}
}
when triggerkey is pressed, it loads the file

Inputs in SDL (on key pressed)

I would like to know how can I detect the press of a key or release of a key in a while loop in SDL. Now, I know you can get the events with SDL like OnKeyPressed, OnKeyReleased, OnKeyHit, etc, but I want to know how to build functions like 'KeyPressed' that returns a boolean, instead of being an event. Example:
while not KeyHit( KEY_ESC )
{
//Code here
}
I know you have already selected an answer.. but here is some actual code of how I typically do it with one array. :)
first define this somewhere.
bool KEYS[322]; // 322 is the number of SDLK_DOWN events
for(int i = 0; i < 322; i++) { // init them all to false
KEYS[i] = false;
}
SDL_EnableKeyRepeat(0,0); // you can configure this how you want, but it makes it nice for when you want to register a key continuously being held down
Then later, create a keyboard() function which will register keyboard input
void keyboard() {
// message processing loop
SDL_Event event;
while (SDL_PollEvent(&event)) {
// check for messages
switch (event.type) {
// exit if the window is closed
case SDL_QUIT:
game_state = 0; // set game state to done,(do what you want here)
break;
// check for keypresses
case SDL_KEYDOWN:
KEYS[event.key.keysym.sym] = true;
break;
case SDL_KEYUP:
KEYS[event.key.keysym.sym] = false;
break;
default:
break;
}
} // end of message processing
}
Then when you actually want to use the keyboard input i.e. a handleInput() function, it may look something like this:
void handleInput() {
if(KEYS[SDLK_LEFT]) { // move left
if(player->x - player->speed >= 0) {
player->x -= player->speed;
}
}
if(KEYS[SDLK_RIGHT]) { // move right
if(player->x + player->speed <= screen->w) {
player->x += player->speed;
}
}
if(KEYS[SDLK_UP]) { // move up
if(player->y - player->speed >= 0) {
player->y -= player->speed;
}
}
if(KEYS[SDLK_DOWN]) { // move down
if(player->y + player->speed <= screen->h) {
player->y += player->speed;
}
}
if(KEYS[SDLK_s]) { // shoot
if(SDL_GetTicks() - player->lastShot > player->shotDelay) {
shootbeam(player->beam);
}
}
if(KEYS[SDLK_q]) {
if(player->beam == PLAYER_BEAM_CHARGE) {
player->beam = PLAYER_BEAM_NORMAL;
} else {
player->beam = PLAYER_BEAM_CHARGE;
}
}
if(KEYS[SDLK_r]) {
reset();
}
if(KEYS[SDLK_ESCAPE]) {
gamestate = 0;
}
}
And of course you can easily do what you're wanting to do
while(KEYS[SDLK_s]) {
// do something
keyboard(); // don't forget to redetect which keys are being pressed!
}
**Updated version on my website: **
For the sake of not posting a lot of source code, you can view a complete SDL Keyboard class in C++ that supports
Single Key Input
Simultaneous Key Combos (Keys all pressed in any order)
Sequential Key Combonations (Keys all pressed in specific order)
http://kennycason.com/posts/2009-09-20-sdl-simple-space-shooter-game-demo-part-i.html (if you have any problems, let me know)
There is an SDL function for this: SDL_GetKeyboardState
Example to check whether left or right CTRL key is pressed:
const Uint8* state = SDL_GetKeyboardState(nullptr);
if (state[SDL_SCANCODE_LCTRL] || state[SDL_SCANCODE_RCTRL]) {
std::cerr << "ctrl pressed" << std::endl;
}
I had this problem in LuaJIT with FFI, this is how I solved it:
Global:
KEYS = {}
Event code:
ev = ffi.new("SDL_Event[1]")
function event()
while sdl.SDL_PollEvent(ev) ~= 0 do
local e = ev[0]
local etype = e.type
if etype == sdl.SDL_QUIT then
return false -- quit
-- os.exit() -- prevents interactive mode
elseif etype == sdl.SDL_KEYDOWN then
if e.key.keysym.sym == sdl.SDLK_ESCAPE then
return false -- quit
-- os.exit()
end
print("Pressed: ", e.key.keysym.scancode, "\n")
KEYS[tonumber(e.key.keysym.sym)] = true
-- print("Pressed: ", (e.key.keysym.sym == sdl.SDLK_w), "\n");
elseif etype == sdl.SDL_KEYUP then
KEYS[tonumber(e.key.keysym.sym)] = false
elseif etype == sdl.SDL_VIDEORESIZE then
-- print("video resize W:".. e.resize.w .. " H:" .. e.resize.h)
width = e.resize.w
height = e.resize.h
onResize()
end
end
return true -- everything ok
end
Update function:
if KEYS[sdl.SDLK_w] == true then
rot = rot + 1
end
Most time i wasted on this:
KEYS[tonumber(e.key.keysym.sym)] = false
Because FFI is returning a CData object, which was used as the array-key, but it needs the integer.
You should have 2 tables of booleans for keys. One table, in which you set keys true or false based on the SDL keydown/keyup events, and another one, that you initialize with false. When checking keyPressed, you just compare the second table key with the first table key, and if different, if second table key is false, then it was pressed, else it was released. After that, you do secondTable[key] := not secondTable[key]. Works!

Resources