如果我有起点,线的角度和长度,我如何计算线的终点?

时间:2015-09-07 14:17:51

标签: libgdx box2d raycasting

第1点,说它是(0,0),我有另一个点应该在10f的距离转过来。然后我将添加度角以使其旋转。我想知道如何计算这个转折的点......

我将使用光线投射,我需要旋转光线(顺时针)来检测碰撞

2 个答案:

答案 0 :(得分:1)

所以你说你有point1point2,两者之间的距离为10f,其中point2将围绕point1旋转,你想要要知道在这种分离之间某个点上的物体是否与它们相交,如下图所示:

view

有一些教程可以获得在互联网上旋转另一个点的数学,例如this one,因为你无法指定Vector2的原点,翻译版本为预览链接到java中提出的代码应该类似于:

public Vector2 rotatePoint(Vector2 center, Vector2 point, float angle) {
    angle = angle * MathUtils.degreesToRadians; // Convert to radians
    float rotatedX = MathUtils.cos(angle) * (point.x - center.x) 
            - MathUtils.sin(angle) * (point.y - center.y) + center.x;
    float rotatedY = MathUtils.sin(angle) * (point.x - center.x) 
            + MathUtils.cos(angle) * (point.y - center.y) + center.y;

    // rotated new position:
    return new Vector2(rotatedX, rotatedY);
}

至于其余的代码(对象之间的交集),我想你正在寻找RayCastCallback接口:

// initial position
Vector2 point1 = new Vector(0, 0);
// Max lenght of view
Vector2 point2 = new Vector(0, 10);
// Position of collision if occur
final Vector2 collisionPoint = new Vector();

@Override
public void render(float delta) {
    //...
    point2 = rotatePoint(point1, point2, 10); // rotate 10º
    // to detect if object at position point1 is seeing something
    world.rayCast(new RayCastCallback(){
        @Override
        public float reportRayFixture(Fixture fixture,  Vector2 point, 
                 Vector2 normal, float fraction) {
            // what do the object saw?     -> fixture
            // where do the object saw it? -> point

            collisionPoint.set(point);

            return 0; // <- return 0 to stop raycasting
        }
    }, point1, point2);
    //...  rotation and other stuffs...
}

reportRayFixture的返回参数包含以下文档:

  

为查询中找到的每个夹具调用。您可以通过返回浮点来控制光线投射的进度:返回-1:忽略此灯具并继续返回0:终止光线投射返回分数:将光线剪切到此点返回1:不要&#39 ; t剪辑光线并继续。传递给回调的Vector2实例将被重用于将来的调用,因此请复制它们!

**重点补充。

基本上它表示您可以逐个检查所有交叉点,但如果您只关心第一个交叉点,请立即返回0。当您想知道对象是否被另一个对象阻止时,这非常有用。在这种情况下,我返回0并将point的值复制到collisionPoint,以便您可以对此值执行任何操作。

this video中可以找到一个非常好的例子。

希望你觉得这很有用。

答案 1 :(得分:0)

你应该考虑使用Intersector类检查你的演员的线是否与身体形状相交。

要计算“视线”线的结束,请使用 Vector2 根据您的演员轮换旋转(这实际上是您问题的答案)

应该看起来像:

    Vector2 sightVector = new Vector2(10f, 0); //the 10f is actually your sight max distance
    sightVector.rotate(actor.getRotation());

    ...

    @Override
    pblic void render(float delta) //it can be also act of the actor
    {
        sightVector.rotate(actor.getRotation());

        Vector2 endOfLine = new Vector2(actor.getX() + sightVector.x, actor.getY() + sightVector.y); //here you are calculating the end of line

        Polygon bodyShape = getBodyShape( theBody ); //you should create a method that will return your body shape

        if( Intersector.intersectLinePolygon(new Vector2(actor.getX(), actor.getY()), endOfLine, bodyShape) )
        {
            //do something
        }

        ...

    }

Intersector具有检查与圆等交点的方法,因此您的身体形状不需要是多边形

相关问题