libGDX中的三角函数 - 速度和角度

时间:2014-09-15 01:11:12

标签: libgdx

对于我的游戏,我想使用三角法。正如我最初搜索的一切都与Actionscript3中的相同。但是我错了。什么都没有奏效。所以在搜索了libGDX论坛和stachoverflow帖子之后我已经玩了#34;用数字和找到解决方案。希望它可以帮助某人

1 个答案:

答案 0 :(得分:0)

如何计算libgdx中的角度以及如何使用三角函数设置x和y速度(为清晰起见,省略了代码):

//variables
private Object object;
private float touchX, touchY, angle, xSpeed, ySpeed;
private final int power = 5;

//touch up event
@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
    touchX = screenX;
    touchY = h - screenY; // screenX gives an inverted y position (y == 0 is at the top)
    setPosition(touchX, touchY);        
}

//set angle and velocity method
public void setPosition(int x, int y){
    //example 1 (velocity is calculated without angle):
    angle = (float) (Math.atan2(y - object.y, x - object.x) * tdg) - 90.0f;
    //at the end there is not always -90.0f. It depends of how the texture (or sth else we 
    //want to rotate) is rotated in .png file. Play with nuber if -90.0f is not good. Use 
    //the scale from -360 to 360
    xSpeed = (x - bx) / 30;
    ySpeed = (y - by) / 30;

    //example 2 (velocity with angle):
    angle = (float) Math.atan2(y - object.y, x - object.x);
    xSpeed = (float) (Math.cos(angle)*power);
    ySpeed = (float) (Math.sin(angle)*power);
    angle = (angle*180/Math.PI) - 90.0f;
}