My 2d project has a portal, where I am just changing the transform.position of player to the exit when the player enters it. I want the player to conserve it's momentum when it comes out of the portal.
Like if it's falling in the portal, it should exit from the portal's end with the same force but in the angle of the portal's end.
Is this possible or is my approach wrong?
CodePudding user response:
Besides that being something you could simply test, when dealing with physics you wouldn't want to do anything via Transform
at all.
So let's say you have
Rigidbody2d player
Transform portalA
Transform portalB
then I would probably do something like e.g.
public static class Rigidbody2dExtensions
{
public static void Teleport(this Rigidbody2d player, Transform from, Transform to)
{
// position including current offset to portal
var localOffset = from.InverseTransformPoint(player.position);
player.position = to.TransformPoint(localOffset);
// and then apply the rotation delta
var rotationDelta = Vector2.SignedAngle(from.up, to.up);
// a) to the rotation itself
player.rotation = rotationDelta;
// b) to the direction of the velocity
player.velocity = Quaternion.Euler(0,0, rotationDelta) * (Vector3) player.velocity;
}
}
The first part
- sets the position via the
Rigidbody2d
instead of theTransform
component. - Allows to use an offset so the player doesn't need to be teleported exactly to the target portal. If you e.g. use colliders it might only touch the portal with the left edge so it will maintain this offset even if the target portal is rotated.
Then the second part as the comments say
- rotates the player according to the portal orientations
- applies this delta rotation also to the
velocity
and thereby maintains the momentum but translated to the new portal orientation