Stop an object in Processing

Viewed 34

I'm planning to make a game using Processing. Basically I've created a character with (x, y) as his coordinates, and a 20x20 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)){
            this.wizard.stop()
     }

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?

1 Answers

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.

Related