Reputation: 139
Currently i am trying to render a rectangle between the mouse and a body the catch is I want the line to have a maximum length.
Meaning when the distance between the 2 points on the screen is less than a certain amount the rectangle should be between the mouse and body. If not the rectangle should be between a radius(point on the line from body to mouse) and the body.
I am using some vector logic to calculate the point to draw but when I seem to go inside my if statement the line which is drawn in under 200 distance just disappears.
ShapeRenderer sr = new ShapeRenderer();
sr.setColor(Color.WHITE);
sr.begin(ShapeRenderer.ShapeType.Filled);
if (ballPosition.dst(mousePos) > 200) {
System.out.println("Entered If!");
//Calculate point a distance away from ballPosition
Vector2 cloneMousePos = new Vector2(mousePos);
Vector2 dir = cloneMousePos.sub(ballPosition);
dir = dir.nor().scl(100);
Vector2 test = ballPosition.add(dir);
mousePos = test;
}
System.out.println("MousePos: " + mousePos.x + ", " + mousePos.y);
sr.rectLine(ballPosition, mousePos, 4f);
sr.end();
This is inside a Screen class I find it strange since when the distance is less than 200 the line draws perfectly, though from printing the x,y
coordinates of the vectors it seems to be checking out.
Prints of the x,y coordinates of mousepos
before moving a distance 200 out of body and after
MousePos: 213.0, 325.0
Entered If!
MousePos: 305.3836, 357.63123
EDIT: On suggestion in the comments I have added some pictures.
Here a line between the ball and mouse is being drawn since the distance is under 200.
while here the distance becomes over 200 and we enter the if statement no line is drawn anymore unless we return to under 200.
Thanks!
Upvotes: 1
Views: 79
Reputation: 7121
Vector2
has a limit
method to limit the length if greater than a certain value.
Vector2 dir = new Vector(mousePos).sub(ballPosition)
dir.limit(200f)
sr.rectLine(ballPosition, dir.add(ballPosition), 4f);
Upvotes: 3