我制作了SpaceInvaders的版本,我希望我的Shoots能够进行对角线移动。我试着谷歌,但我可以弄明白该怎么做。
我有类实体:
public abstract class Entity extends Parent{
protected double x;
protected double y;
protected double dx;
protected double dy;
private Rectangle me = new Rectangle();
private Rectangle him = new Rectangle();
Image ref;
StackPane root;
ImageView content;
public Entity(Image ref,int x,int y, StackPane root) {
this.ref=ref;
this.root=root;
this.x = x;
this.y = y;
content = new ImageView();
content.setSmooth(true);
content.setImage(ref);
content.setScaleX(Game.scalar);
content.setScaleY(Game.scalar);
content.setTranslateX(this.x);
content.setTranslateY(this.y);
content.setRotate(0);
Game.root.getChildren().add(content);
}
public void move(long delta) {
this.x += (delta * this.dx) / 1000;
this.y += (delta * this.dy) / 1000;
content.setTranslateX(this.x);
content.setTranslateY(this.y);
}
现在,我怎么能设置对角线运动?我用拍摄实体打印了游戏。
答案 0 :(得分:4)
您应该使用三角函数,尤其是sin
和cos
。标准java类Math
具有这些方法。
例如,我们可以认为从底部到顶部的子弹以90度的角度(0从左到右,180从右到左,270从上到下):
double angle = 90.0;
double angleInRadians = Math.toRadians(angle); // convert from degrees to radians
x += Math.cos(angleInRadians); // cos of 90 is 0, so no horizontal movement
y += Math.sin(angleInRadians); // sin of 90 is 1, full vertical movement
要对角线只使用不同的角度,例如60度,子弹将水平和垂直移动:
double angle = 60.0;
double angleInRadians = Math.toRadians(angle); // convert from degrees to radians
x += Math.cos(angleInRadians); // cos of 60 is 0.58.., so a bit of horizontal movement
y += Math.sin(angleInRadians); // sin of 60 is 0.80.., a decent amount of vertical movement
下面的图片展示了我们想要实现的目标,基本上找到要添加到delta x
位置的delta y
和origin
才能到达destination
位置,并不是彼此垂直的。
现在让我们来看看sine
和cosine
代表什么:
(来源:维基百科。)
我们可以注意到相似之处:点O
和P
分别是我们的origin
和destination
,而sin θ
和cos θ
对应到delta y
和delta x
。
将这些概念应用于我们的情况,我们最终得到:
正弦和余弦需要一个角度,它将定义我们物体的运动方向。
它们将返回介于-1和1之间的值,因此如果我们想要更改对象移动"速度"那么我们需要将它与系数相乘。
答案 1 :(得分:0)
根据您提供的有限信息,我假设x
和y
是您的宇宙飞船的坐标,而dx
和dy
是您的坐标。射弹的目标。您可以使用Math.atan2()
计算射弹图像的旋转度,并将其提供给您所拥有的content.setRotate()
。
// consider your spaceship an origin in coordinate system
double relativeX = this.dx - this.x;
double relativeY = this.y - this.dy;
double degree = Math.toDegrees(Math.atan2(relativeY, relativeX));
// rotate a projectile image counterclockwise from horizontal direction
content.setRotate(90 - degree);