Hi, all! I just got a portal system to work. One portal is on the wall, facing forwards, and one is on the ground, facing up. How would I make it so that when my character enters one portal, when he spawns at the other, the velocity from when he entered the first portal is redirected in the direction the other is facing?
E.X. Like when I run at the one in the wall, and when I pop out at the one on the floor, instead of just falling back down into the portal on the floor immediately, the force from my running at the wall is redirected upwards (the way the portal on the ground is facing) and I have a couple seconds in the air before I enter it again?
2 Answers
2
Try this script.
Set up a trigger and attach this script to it.
Bind exit to a point where the object will jump out from.
You can probably go on from there to customize it for your needs.
using UnityEngine;
public class Portal : MonoBehaviour
{
public Transform exit;
void OnTriggerEnter(Collider collider)
{
var velocity = collider.rigidbody.velocity;
velocity = Vector3.Reflect(velocity, transform.forward);
velocity = transform.InverseTransformDirection(velocity);
velocity = exit.TransformDirection(velocity);
collider.rigidbody.velocity = velocity;
collider.rigidbody.position = exit.position;
}
}
Save the velocity magnitude somewhere
var mag:float = rigidbody.velocity.magnitude;
And when you spawn the character at the other portal take set the velocity
rigidbody.velocity = portal.transform.forward * mag;
You might want to ditch the reflect part, I am not too sure of your needs.
– StatementJust a fun FYI which helped me understand quaternions a bit better. The line "velocity = transform.InverseTransformDirection(velocity);" is the same as "velocity = Quaternion.Inverse(transform.rotation) * velocity;" And the line "velocity = exit.TransformDirection(velocity);" is the same as "velocity = exit.transform.rotation * velocity;" Both approaches convert the vector from world->local, and then from local->world.
– anon86285172