# Moving object Speed increases when key pressed

**URL:** <https://discourse.processing.org/t/moving-object-speed-increases-when-key-pressed/16993>\
**Category:** Coding Questions\
**Created:** [January 9, 2020, 8:24pm UTC](https://discourse.processing.org/t/moving-object-speed-increases-when-key-pressed/16993 "2020-01-09T20:24:49Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![jegg](https://avatars.discourse-cdn.com/v4/letter/j/71c47a/32.png) [@jegg](https://discourse.processing.org/u/jegg)\
**Post date:** [January 9, 2020, 8:24pm UTC](https://discourse.processing.org/t/moving-object-speed-increases-when-key-pressed/16993/1 "2020-01-09T20:24:49Z")

</div>

I need help with a code i want to increase the speed of a moving object when the key “P” is pressed i cant find the code. I need this for a project  
Here is my code  
float x = 100;  
float y = 100;

float xSpeed = 0;  
float ySpeed = 0;

boolean keyLeft, keyRight, keyUp, keyDown;

void setup(){

size(600,600);

}

void draw(){

background(255);  
fill(255,0,0);  
rect(0,0,600,250);  
fill(0,255,0);

rect(x, y, 50, 50);

countSpeed(); //Change speed based on current keys pressed.  
changePosition(); //Change position based on speed.

xSpeed \*= 0.9; //Apply some drag so that the square wouldn’t fly off the screen indefinitely  
ySpeed \*= 0.9;

}

void countSpeed(){  
if(keyLeft) xSpeed-= 0.5;  
if(keyRight) xSpeed+= 0.5;  
if(keyUp) ySpeed-= 0.5;  
if(keyDown) ySpeed+= 0.5;  
}

void changePosition(){  
x+=xSpeed;  
y+=ySpeed;  
}

void keyPressed() {  
if (key == CODED) {  
if (keyCode == UP) {  
keyUp = true;  
}  
if (keyCode == DOWN) {  
keyDown = true;  
}  
if (keyCode == LEFT) {  
keyLeft = true;  
}  
if (keyCode == RIGHT) {  
keyRight = true;  
}  
}  
}  
void keyReleased() {  
if (key == CODED) {  
if (keyCode == UP) {  
keyUp = false;  
}  
if (keyCode == DOWN) {  
keyDown = false;  
}  
if (keyCode == LEFT) {  
keyLeft = false;  
}  
if (keyCode == RIGHT) {  
keyRight = false;  
}  
}

}

---

<div class="post-metadata">

**Author:** ![kll](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/kll/32/964_2.png) [@kll](https://discourse.processing.org/u/kll)\
**Post date:** [January 10, 2020, 1:12am UTC](https://discourse.processing.org/t/moving-object-speed-increases-when-key-pressed/16993/2 "2020-01-10T01:12:10Z")

</div>

please format your code posting by pasting it into the

```auto
</> code button

```

of the editor header menu ( context name: Preformatted text )  
it looks like  
```  
type or paste code here  
```

also can use the ``` manually above and below your code.

thank you.

* * *

now we need you to REPAIR your above CODE POSTING,  
not make a new / better post.  
( just think about the hundred peoples opening your topic in the future )

* * *

* * *

> [@jegg](#):
>
> xSpeed-= 0.5;

```auto
xSpeed = -0.5;

```

what is the difference?
