开发者

How to move 2 xna sprites away from eachother dynamically?

I have two items, lets call them Obj1 and Obj2... Both have a current position pos1 and pos2.. Moreover they have current velocity vectors speed1 and speed2 ... How can I make sure that if their distances are getting closer (with checking current and NEXT distance), they will move farther away from eachother ?

I have a signed angle function that gives me the signed angle between 2 vectors.. How can I utilize it to check how much should I rotate the speed1 and speed2 to move those sprites from eachother ?

    public float signedAngle(Vector2 v1, Vector2 v2)
    {
        float perpDot = v1.X * v2.Y - v1.Y * v2.X;

        return (float)Math.Atan2(perpDot, Vector2.Dot(v1, v2));
    }

I check the N开发者_C百科EXT and CURRENT distances like that :

float currentDistance = Vector2.Distance(s1.position, s2.position);

Vector2 obj2_nextpos = s2.position + s2.speed + s2.drag;
Vector2 obj1_nextpos = s1.position + s1.speed + s1.drag;

Vector2 s2us = s2.speed;
s2us.Normalize();
Vector2 s1us = s1.speed;
s1us.Normalize();

float nextDistance = Vector2.Distance(obj1_nextpos , obj2_nextpos );

Then depending whether they are getting bigger or smaller I want to move them away (either by increasing their current speed at the same direction or MAKING THEM FURTHER WHICH I FAIL)...

if (nextDistance < currentDistance )
{       
float angle = MathHelper.ToRadians(180)- signedAngle(s1us, s2us);
s1.speed += Vector2.Transform(s1us, Matrix.CreateRotationZ(angle)) * esc;
s2.speed += Vector2.Transform(s2us, Matrix.CreateRotationZ(angle)) * esc;
}

Any ideas ?


if objects A and B are getting closer, one of the object components (X or Y) is opposite.

in this case Bx is opposite to Ax, so only have to add Ax to the velocity vector of object B, and Bx to velocity vector of object A

How to move 2 xna sprites away from eachother dynamically?


If I understood correctly, this is the situation and you want to obtain the two green vectors.

How to move 2 xna sprites away from eachother dynamically?

The red vector is easy to get: redVect = pos1 - pos2. redVect and greenVect2 will point to the same direction, so the only step you have is to scale it so its length will match speed2's one: finalGreenVect2 = greenvect2.Normalize() * speed2.Length (although I'm not actually sure about this formula). greenVect1 = -redVect so finalGreenVect1 = greenVect1.Normalize() * speed1.Length. Then speed1 = finalGreenVect1 and speed2 = finalGreenVect2. This approach will give you instant turn, if you prefer a smooth turn you want to rotate the speed vector by:

angle = signedAngle(speed) + (signedAngle(greenVect) - signedAngle(speed)) * 0.5f;

The o.5f is the rotation speed, adjust it to any value you need. I'm afraid that you have to create a rotation matrix then Transform() the speed vector with this matrix.
Hope this helps ;)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜