Rotation in a Vector2d class in Java

2019-09-04 08:23发布

I've been working on this for one hour, just can't get it.

I have a Vector2d class:

public class Vector2d
{
    public double x = 0.0;
    public double y = 0.0;

    ....
}

This vector class has a rotate() method which is causing me trouble.

The first snippet seems to make the x and y values smaller and smaller. The second one works just fine! Am I missing something simple here?

public void rotate(double n)
{
    this.x = (this.x * Math.cos(n)) - (this.y * Math.sin(n));
    this.y = (this.x * Math.sin(n)) + (this.y * Math.cos(n));
}

This works:

public void rotate(double n)
{
    double rx = (this.x * Math.cos(n)) - (this.y * Math.sin(n));
    double ry = (this.x * Math.sin(n)) + (this.y * Math.cos(n));
    x = rx;
    y = ry;
}

I just can't spot any difference there

1条回答
别忘想泡老子
2楼-- · 2019-09-04 09:11

The first line sets the value of this.x which is then used in the second line when what you really want is the original value of this.x. The second version works fine because you don't alter this.x.

查看更多
登录 后发表回答