Casting to int
always truncates towards 0. To round, you can use Math.round()
instead. However, that always rounds halves up:
class Test {
public static void main(String[] args) {
System.out.println(Math.round(-7.7)); // -8
System.out.println(Math.round(-7.5)); // -7
System.out.println(Math.round(-7.2)); // -7
System.out.println(Math.round(+7.2)); // 7
System.out.println(Math.round(+7.5)); // 8
System.out.println(Math.round(+7.7)); // 8
}
}
Are you sure you want to round halves away from zero? If so, Math.round()
won't quite do what you want. You could write your own method though:
public static long customRound(double x) {
return x >= 0 ? (long) (x + 0.5)
: (long) (x - 0.5);
}
This will always round away from zero, by either adding or subtracting 0.5 first (depending on the sign) and then truncating towards 0. That produces the same values as before, except that -7.5 is rounded to -8.
EDIT: I suspect the remaining problem is almost certainly due to the division being performed in integer arithmetic. We don't know the types of any of your values, but I suspect they're all int
, which would lead to that problem. If you make either of the operands of the division double
, it will perform the division in double
arithmetic instead. The easiest way to do that - which would also increase readability - is probably to extract some of the expressions to separate variables, and cast where necessary:
double xDifference = e.getX() - Frame.x;
double widthRatio = Screen.myWidth / (double) World.worldWith;
double x = (xDifference / widthRatio) - 8;
Player.targetx = (int) Math.round(x);
If that still doesn't work, at least you'll have a much easier time seeing what's wrong.