[SOLVED] Stop an object in Processing


This Content is from Stack Overflow. Question asked by Minh Long Duong

I’m planning to make a game using Processing. Basically I’ve created a character with (x, y) as his coordinates, and a 20×20 block, also with a coordinate (x1, y1). I want to keep the character from passing through the block.
I’ve somewhat successfully figured out how to detect collision (although the numbers aren’t perfect yet):

if((this.wizard.getX() < this.brickwall.getX()+10 & this.wizard.getX() > this.brickwall.getX()-10) && (this.wizard.getY() < this.brickwall.getY()+10 & this.wizard.getY() > this.brickwall.getY()-10)){

With stop being the function to stop the character.
But I haven’t figured out a way to make the character stop yet.
I’ve tried something like this

this.x = this.x
this.y = this.x

whenever the stop() method is called in the wizard class, but it doesn’t work.
Can anyone help me?


If you want him to stop, you need the concept of speed.
This requires 2 additional member variables, velocityX and velocityY.

When the input comes, you set the velocity to 1 or -1 (or any other fitting number)

this.velocityX = 1

Movement now comes down to

this.x += this.velocityX
this.y += this.velocityY

In case you want to stop the character

this.velocityX = 0
this.velocityY = 0

In case you already moved the character INTO an object and need to get him back out, write:

// reverses last move
this.x -= this.velocityX
this.y -= this.velocityY

// sets speed to 0
this.velocityX = 0
this.velocityY = 0

But usually movement should always be done AFTER the check.

This Question was asked in StackOverflow by Minh Long Duong and Answered by JayC667 It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?