How does the velocity of a ball flying throw a portal change when the portal is rotated?

So i tried a lot of stuff but nothing worked.
I hope someone of you is better in physics then me.
I think the picture represent my problem pretty good but if you need any details let me know.

Hi @OneCode-Official

The complexity of the code to do this depends on a number of things:

  1. Will your ball enter the portal at
    an angle? Or will it always enter
    straight?
  2. Is your ball also affected
    by gravity or other external forces
    when it enters?
  3. Does your ball have
    any angular velocity?
  4. Will rotation
    need to be taken into account?
  5. Is there any change to speed when going through the portal?

I’ll assume the answers to 3, 4 and 5 are all no.

If your ball always exits straight all you need is

Vector3 currentVelocity = rigidbody.velocity; // rigidbody = ball.GetComponent<Rigidbody>();
Vector3 newVelocity = exitPortal.transform.forward * currentVelocity.magnitude;

If you want your ball to exit at the same relative angle with which it entered then

Vector3 currentVelocity = rigidbody.velocity;
    Vector3 enterVelocity = enterPortal.transform.InverseTransformDirection(currentVelocity);
    Vector3 exitVelocity = exitPortal.TransformDirection(enterVelocity);

// This takes the world space ball's velocity vector, and gives a velocity vector that is local to the enter portal. This vector can then be applied at the exit portal to get the same relative direction as in entry.

It’s important to note that magnitude is unaffected by InverseTransformDirection().


I haven’t tried the code myself but it should work in principle. Let me know if it doesn’t work or if there are more variables to consider in finding a solution.

From your question’s tags, it looks like your game is 2d, which makes this so much easier. What you need to do is find a vector that can represent the difference of your velocity and the rotation of your portal. To do this you need to divide your entrance portal’s .foreward by your ball’s velocity. You then need to multiply your exit portals .foreward by the new vector.

Vector3 difference = enterPortal.transform.foreward / ball.rigidbody.velocity;
ball.transform.position = exitPortal.transform.position;
ball.rigidbody.velocity = exitPortal.transform.foreward * difference;

Do note that you can’t actually get ball.rigidbody, you’ll need to reference the rigidbody2d in some other variable. If this doesn’t work (which it very well might not, I’m not incredibly confident in my vector maths) you might want to try saving the magnitude of your velocity. This would make the code look like this:

Vector3 difference = enterPortal.transform.foreward / ball.rigidbody.velocity;
float magnitude = ball.rigidbody.velocity.magnitude;
ball.transform.position = exitPortal.transform.position;
Vector3 newVelocity = exitPortal.transform.foreward * difference.normalized * magnitude;
ball.rigidbody.velocity = newVelocity;