Java - 对角线运动

时间:2016-05-31 16:32:42

标签: java path-finding

我制作了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);


    }

现在,我怎么能设置对角线运动?我用拍摄实体打印了游戏。

Thaks。 Alien Shoot

2 个答案:

答案 0 :(得分:4)

您应该使用三角函数,尤其是sincos。标准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 yorigin才能到达destination位置,并不是彼此垂直的。

The situation representation

现在让我们来看看sinecosine代表什么:

sine and cosine representation

(来源:维基百科。)

我们可以注意到相似之处:点OP分别是我们的origindestination,而sin θcos θ对应到delta ydelta x

将这些概念应用于我们的情况,我们最终得到:

sine and cosine applied

正弦和余弦需要一个角度,它将定义我们物体的运动方向。

它们将返回介于-1和1之间的值,因此如果我们想要更改对象移动"速度"那么我们需要将它与系数相乘。

答案 1 :(得分:0)

根据您提供的有限信息,我假设xy是您的宇宙飞船的坐标,而dxdy是您的坐标。射弹的目标。您可以使用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);