- Home /
How can I make a player teleport?
Hi! I am using javascript to code my 2d platforming game and I wanted to know how you can make someone teleport about 100 pixels away from their current position.
For example if I press space wherever the person is currently standing it would basically just shift over a 100 pixels. But if something is in between the 100 pixels like a wall it will pass through it.
Does anyone know how to do this in Javascript?
is there away to limit how far it can go? I did: if (Input.GetButtonDown("shiftRight")) { transform.position=Vector3(shiftDistance,0,0); }
and shiftDistanc=1 I tried making it less like .1 but it doesn't seem to make it teleport any closer
You should use translate, in s$$anonymous$$d of directly changing the position, to avoid problems with the physics.
at his level it will be no problem, RC
just do this
transform.position.x += 2.0;
see how that works for you champ !
Answer by RC-1290 · Oct 13, 2012 at 04:59 PM
For a basic teleport effect, you can simply translate the player forward.
But you mention that you want the player to teleport beyond objects that are in their way. To do that, you could cast a ray from the player's initial position, to the target position. If an object is hit, you find the first clear area beyond the object, to where the player can stand again.
One basic method to do this, would be to fire a ray from 1 meter beyond the original target, back to the player's position, then 2 meters, then 4 (doubling the distance every time), until the distance from where the ray is fired to the first object that is hit, is high enough for the player to fit there.
You could also come up with different or more complex solutions, to make sure you don't teleport through multiple objects.
[edit] Another method for finding a place beyond the object: Fire a ray from within the object in the direction the player is teleporting in, ignoring that first obstacle, then fire a ray back towards to the original player position, to ensure there is enough room for the player to fit there.
is there any way to detect collision without rays? Or ins$$anonymous$$d make the rays form a collision box of where the player could land so if a block is in there it can't teleport.
Capsule Cast is probably what you are looking for. It basically works like a really big ray. Capsules are often used as stand-in for the player, because you can make it roughly the size and shape of a human, while it costs a lot less CPU time than using the actual player mesh.
The other colliders in Unity are most useful for its built in collision detection. Those collisions are automatically calculated each Fixed Update. With capsule cast or one of the other methods, you don't have to wait for the next frame, before getting results.
@mkjrfan , it will be almost impossible for you to move ahead unless you get really good at using raycasting
it is used everywhere, constantly, in games I'm afraid to say !
good luck !