How to pause/play a sketch in processing with the same button? - processing

I'm trying to implement a pause/play for a sketch with the same key, for example if I press p the sketch should stop and if I press p again, the sketch should start again. So far I used the noLoop()/loop() to do this but with two different keys (p for pause, r for start). It does work if I use keyPressed() and keyReleased() but this means to hold down the key but this doesn't answer my question. Also in the pause mode I used redraw() for a single step while noLoop() and works good.
Here is some code I tried so far with two different keys:
public void draw(){
background(random(255));
}
public void keyPressed(){
if ( key == 'p' )
noLoop();
if ( key == 'r' )
loop();
if ( key == 's' )
redraw();
}
And this is the code with the same key:
public void draw(){
background(random(255));
}
public void keyPressed(){
if ( key == 'p' )
noLoop();
if ( key == 'p' )
loop();
if ( key == 's' )
redraw();
}
In this case when I press key it doesn't have any effect.
And the last one I tried is this:
public void draw(){
background(random(255));
}
public void keyPressed(){
if ( key == 'p' )
noLoop();
else
loop();
if ( key == 's' )
redraw();
}
In this case when I press 'p' it stops the sketch but is doesn't play again. Because of the 'else' it plays again when I press any key including 's' which suppose to be just for a single step.
Any help is more than welcome.
Thanks!

Please try to post a MCVE that we can copy and paste to run ourselves. The code you've posted is almost a MCVE, but please include a draw() function so we can see exactly the same thing as you.
Here's a simple MCVE that demonstrates the problem you're having:
void draw() {
background(random(255));
}
public void keyPressed() {
if ( key == 'p' ) {
noLoop();
}
if ( key == 'p' ) {
loop();
}
}
This code will show a randomly flashing background. If you press the P key, you're expecting it to pause, but it just keeps flashing.
You need to get into the habit of stepping through your code to understand exactly what it's doing. Read through the keyPressed() function line by line, and imagine what the code will do when you press the P key.
The first if statement checks whether the key is P, and since it is, it calls the noLoop() function. Then the second if statement checks whether they key is P, and since it is, it calls the loop() function. This reverses the call to noLoop() we just made, which makes it appear as though nothing happens.
You need to track the state of your sketch. In your case, you need to track whether the sketch is currently paused. You could use a single boolean variable for this. Then use that variable to make sure you do the right thing when the P key is pressed. Something like this:
boolean paused = false;
void draw() {
background(random(255));
}
public void keyPressed() {
if ( key == 'p' ) {
paused = !paused;
if (paused) {
noLoop();
} else {
loop();
}
}
}

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.

Is it possible to put a variable in a key() function?

I am trying to make a calculator in processing. My thought process for how this is going to work is to make a function for if a certain number is pressed on the keyboard. So I would create some sort of for loop or array even that would sense when a number is pressed, and then return true if it goes through the if statements, however, in order for this to work, I would need to put a variable in the place of a specific key on the keyboard. Is this possible?
Code (so far):
void setup() {
size(800,600);
}
void draw() {
background(0);
Nums.create();
}
class Nums {
void create() {
for (int i = 0; i < 9; i++) {
zero(i);
}
}
boolean zero(int amnt) {
if (keyPressed) {
if (key == amnt) {
return true;
} else {
return false;
}
}
}
}
They keyPressed variable and the functions like keyPressed() and keyReleased() are specifically for keyboard input. They don't, and shouldn't, be concerned with on-screen buttons that you click with the mouse.
Instead, you should probably use the mousePressed() function to detect when the mouse is clicked, and then use if statements to figure out which button was clicked. You can use point-rectangle collision detection to detect which button was clicked. There's also a button sketch in the examples that come with the Processing editor.

Controlling two objects' movement in ping pong game in Processing

I'm trying to build a ping pong game with Processing language. For this two-player game I have two controllers at each end of the 'table'. I coded the movements of the players (up and down) by binding them to the keys:
- w and s for player 1
- o and l for player 2
Although this works when I press them one at a time, I cannot figure out how to make them move simultaneously, as in pressing both w and o at the same time.
Here is my code:
int x=535;
int y=350;
int dx=5;
int dy=5;
int pX=10;
int pY=520;
int pX1=1870;
int pY1=520;
int pS=5;
void setup() {
size(1920,1080);
}
void draw() {
background(0);
rect(960,0,5,1080);
rect(pX,pY,40,150);
rect(pX1,pY1,40,150);
ellipse(x,y,50,50);
x=x+dx;
y=y+dy;
bounce();
move();
move1();
}
void bounce(){
if(x>=1920 || x<=0){
dx=-dx;
}
if(y>1080 || y<0){
dy=-dy;
}
}
void move(){
if(keyPressed){
if(key == 's'){
pY+=pS;
}else if (key == 'w'){
pY-=pS;
}
}
}
void move1() {
if(keyPressed){
if(key == 'l'){
pY1+=pS;
}else if (key == 'o'){
pY1-=pS;
}
}
}
What you want to do is create a boolean value for each key you care about. Then in the keyPressed() function, you set the corresponding variable to true, and in the keyReleased() function, you set the corresponding variable to false. Then in your draw() function, you check the variables to determine which keys are pressed.
Shameless self-promotion: I wrote a tutorial on getting user input available here. Check out the Handling Multiple Keys section.

How can I make the image disappear in Processing

I'm using Processing 3.0.1 which is the latest version.
I successed to display the image when I pressed a certain key.
For example, when I press key 'a', then the image will be displayed.
I also want to make the image disappear when I press another key.
However, I can't find a way to do this.
If anyone knows how to do this, please help me
Here is the code
PImage Onepiece1, Onepiece2;
void setup(){
size(600,600);
Onepiece1 = loadImage("Onepiece1.jpg");
Onepiece2 = loadImage("Onepiece2.jpg");
}
void draw(){
}
void showimage1(){
image(Onepiece1,10,10);
}
void keyPressed(){
if(key == 'a'){
showimage1();
}
else if(key == 'b'){
// I want to make the image disappear when I press 'b'
}
println(key);
}
For this simple scenario #Majlik suggestion is ok, but usually it's not a good idea to draw in callback functions like keyPressed(). Instead use a flag to drive drawings in draw(), like:
Untested
PImage Onepiece1, Onepiece2;
boolean showimage = false;
void setup(){
size(600,600);
Onepiece1 = loadImage("Onepiece1.jpg");
Onepiece2 = loadImage("Onepiece2.jpg");
background (255);
}
void draw(){
background (255);
if(showImage){
showImage1();
}
}
void showimage1(){
image(Onepiece1,10,10);
}
void keyPressed(){
if(key == 'a'){
showImage = true;
}
else if(key == 'b'){
showImage = false;
}
println(key);
}
For the simple scenario like this you just need to redraw image with anything. Best practice is to use background() function. So your reaction to pressing b could look like:
if(key == 'b'){
background(99);
}
Also it is good practice to have specified same background color at the beginning inside setup() function:
void setup(){
size(600,600);
...
background(99);
}

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);
}

Resources