Reputation: 1
how to move my entity's x coordinate to the desired x coordinate by having a speed and move to that x coordinate using that speed instead of directly change to that coordinate
if(this.wizard.x % 20 != 0){
if(this.facing.equals("left")){
this.wizard.x -= this.wizard.x % 20;
}
if(this.facing.equals("right")){
this.wizard.x += 20 - this.wizard.x % 20;
}
}
if(this.wizard.y % 20 != 0){
if(this.facing.equals("up")){
this.wizard.y -= this.wizard.y % 20;
}
if(this.facing.equals("down")){
this.wizard.y += 20 - this.wizard.y % 20;
}
}
I used this code to just change the x coordinate directly, is there a way to set the int speed =2 and then just this.x += speed or this.x-= speed to move the wizard to the wanted x coordinate?
I hope a function could be able to move the wizard to the wanted x coordinate
Upvotes: 0
Views: 50
Reputation: 1155
Your question is not detailed enough for us to understand exactly what effect you want, what the problems with your current approach are, how your character is controlled etc, so this is a "best guess" answer.
The code below is a minimal example of how you can control an object with a specified speed and move it from its current position to a target position selected via a left mouse click. The motion is very simplistic with no acceleration/deceleration effect or other physics. If you want such effects, I suggest you play around with the code first and then look up linear interpolation.
Rect r;
void setup(){
size(500, 500);
r = new Rect(width/2, height/2, 1.5f);
}
void draw(){
background(255);
r.update();
r.display();
// Set new target position with mouse click
if (mousePressed && mouseButton == LEFT) r.setTargetPosition(mouseX, mouseY);
}
class Rect {
PVector position;
float speed;
PVector targetPosition;
Rect(int x, int y, float speed){
position = new PVector(x, y);
this.speed = speed;
targetPosition = position;
}
void setTargetPosition(int targetX, int targetY){
targetPosition = new PVector(targetX, targetY);
}
void update(){
// Calculate distance vector between current position and target position
PVector distance = PVector.sub(targetPosition, position);
// Make sure to stop the motion when it reaches the target position "close enough"
if (distance.mag() < speed) targetPosition = position;
// Add the distance vector, scaled by speed, to the position vector
position.add(distance.setMag(speed));
}
void display(){
// Draw a dot at the target position
fill(0, 255, 0);
ellipse(targetPosition.x, targetPosition.y, 10, 10);
// Draw rectangle
fill(255, 0, 0);
rectMode(CENTER);
rect(position.x, position.y, 50, 50);
}
}
Upvotes: 1