简体   繁体   English

二维Java运动

[英]Java Movement in 2d

I've used something like this for movement in 2d projects before and it's always worked. 之前,我曾在2d项目中使用过类似的方法,但它始终有效。 I'm using it right now and its giving me the correct angles for some outputs, and the wrong angles. 我现在正在使用它,它为我提供了一些输出的正确角度和错误的角度。 I think there is just some error in my trig that I've gotten wrong. 我认为在我的触发中只有一些错误,我弄错了。 I've checked it about a million times though. 我已经检查了大约一百万次。 Prolly just auto correcting the error in my head. Prolly只是自动纠正了我头脑中的错误。 Here is some example output, and the evil codes. 这是一些示例输出以及错误代码。

this(x,y): (500.0, 250.0)
dest(x,y): (400.0, 300.0)
DeltX: 100.0
DeltY: -50.0
Angle: 0.46364760900080615 //about 26.56°, should be 206.56° (26.56+pi) i think
XVELOC: 0.08944272
YVELOC: 0.04472136

public void Update(long deltaTime){
        if(this.destination == null){
            return;
        }

        this.x += this.x_velocity * deltaTime;
        this.y += this.y_velocity * deltaTime;

        if(Math.abs(this.x-destination.x) < 1 && Math.abs(this.y-destination.y) < 1){
            destination.arrive(this);
        }
    }

    public void setPath(){
        if(this.destination == null){
            return;
        } 

        double delta_x = (double) (this.x-this.destination.x);
        double delta_y = (double) (this.y-this.destination.y);
        int sign_x = (int)Math.signum(delta_x);
        int sign_y = (int)Math.signum(delta_y);
        double radian_angle = Math.atan((delta_x/delta_y));
        if(sign_x > 0 && sign_y > 0)
            radian_angle += Math.PI;
        else if(sign_x > 0 && sign_y < 0)
            radian_angle += Math.PI/2;
        else if(sign_x < 0 && sign_y > 0)
            radian_angle += 3*Math.PI/2;

        System.out.println("DeltX: "+delta_x);
        System.out.println("DeltY: "+delta_y);
        System.out.println("Angle: "+radian_angle);

        this.x_velocity = this.max_velocity*(float)Math.cos(radian_angle);
        this.y_velocity = this.max_velocity*(float)Math.sin(radian_angle);

        System.out.println("XVELOC: "+x_velocity);
        System.out.println("YVELOC: "+y_velocity);
    }

Try using atan2 - it's made to handle this for you 尝试使用atan2它是为您处理的

double delta_x = (double) (this.x-this.destination.x);
double delta_y = (double) (this.y-this.destination.y);
double radian_angle = Math.atan2(delta_y,delta_x); // arguements are y,x not x,y

http://download.oracle.com/javase/6/docs/api/java/lang/Math.html#atan2%28double,%20double%29 http://download.oracle.com/javase/6/docs/api/java/lang/Math.html#atan2%28double,%20double%29

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM