Reputation: 59
My title probably does not make much sense which is why I am having a bit of an issue googling my problem.
I am trying to move a shape on the screen from one set of X/Y coordinates to another in a direct line. So for example,
This is the class method for setting the new target direction.
void setTargetPosition(int targetX, int targetY) {
xTar = targetX;
yTar = targetY;
if (xPos > xTar)
xDir = -1;
else
xDir = 1;
if (yPos > yTar)
yDir = -1;
else
xDir = 1;
}
This would set the Direction of the X/Y variables and the following code would move the player on the screen.
void drawPlayer() {
fill(circleColour);
circle(xPos,yPos,35);
//stops player from moving once target destination has been reached
if (xPos == xTar)
xDir = 0;
if (yPos == yTar)
yDir = 0;
xPos += xDir;
yPos += yDir;
}
The above code does work mostly as intended but I need to find a way to proportionally change the X/Y coordinate so that it's more of a 'direct line' to the destination.
Sorry if this does not make sense. I don't know the right terms to use.
Upvotes: 1
Views: 795
Reputation: 211126
You have to use floating point values for the computation of the movement rather than integral values:
float xTar;
float yTar;
float xPos;
float yPos;
setTargetPosition
just set xTar
and yTar
:
void setTargetPosition(float targetX, float targetY) {
xTar = targetX;
yTar = targetY;
}
In drawPlayer
you have to compute the direction vector (PVector
) from the objects position to the target:
PVector dir = new PVector(xTar - xPos, yTar - yPos);
if the length of the vector (mag()
) is greater than 0, the you have to move the object:
if (dir.mag() > 0.0) {
// [...]
}
If you have to move the object, then compute the Unit vector by normalize()
. Note, the length of a unit vector is 1. Multiply the vector by a certain speed by mult()
. This scales the vector to a certain length. Ensure that the length of the vector is not greater than the distance to the object (min(speed, dir.mag())
). Finally add the components of the vector to the position of the object:
dir.normalize();
dir.mult(min(speed, dir.mag()));
xPos += dir.x;
yPos += dir.y;
See the example:
class Player {
float xTar;
float yTar;
float xPos;
float yPos;
color circleColour = color(255, 0, 0);
Player(float x, float y)
{
xTar = xPos = x;
yTar = yPos = y;
}
void setTargetPosition(float targetX, float targetY) {
xTar = targetX;
yTar = targetY;
}
void drawPlayer() {
fill(circleColour);
circle(xPos,yPos,35);
float speed = 2.0;
PVector dir = new PVector(xTar - xPos, yTar - yPos);
if (dir.mag() > 0.0) {
dir.normalize();
dir.mult(min(speed, dir.mag()));
xPos += dir.x;
yPos += dir.y;
}
}
}
Player player;
void setup() {
size(500, 500);
player = new Player(width/2, height/2);
}
void draw() {
background(255);
player.drawPlayer();
}
void mousePressed() {
player.setTargetPosition(mouseX, mouseY);
}
Upvotes: 1