我的图像以逆时针方向旋转.现在,我希望它在触摸墙壁期间或随时随地移动.问题是我做不到,请帮我解决这个问题. 这是我的代码: private double x;private double y;private double speed;public void m
这是我的代码:
private double x; private double y; private double speed; public void move(long dt) { double dt_s = dt / 1e9; double dx = speed * dt_s; double dy = speed * dt_s; final double right_border = 100; final double up_border = 100; final double down_border = 0.0; final double left_border = 0.0; x += dx; if (x >= right_border) { x = right_border; if (y >= down_border) { y += dy; } } if (y > up_border) { y = up_border; if (x >= left_border) { speed *= -1; } } if (x <= left_border) { x = left_border; if (y <= up_border) { y += dy; } } if (y < down_border) { y = down_border; if (x <= right_border) { speed *= -1; } } }首先,你必须解决你的班级无方向的问题 – 你有速度,但你的方向固定在东北45度(增量x和y相同).
向您的班级添加方向,如下所示:
... private double speed; private double angle; // in radians - makes math easier public void move(long dt) { ... double dx = speed * dt_s * Math.sin(angle); double dy = speed * dt_s * Math.cos(angle); ...
现在向随机方向前进:
myObject.setAngle(Math.PI * 2 * Math.random()); // Math.PI * 2 = 360 degrees
如果撞墙,则必须将角度限制在远离您正在击中的墙壁的角度.我会把它留给你,但它会采取以下形式:
myObject.setAngle(minAngle + ((maxAngle - minAngle) * Math.random()));