> For the complete documentation index, see [llms.txt](https://docs.decentraland.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.decentraland.org/creator/content-creator-es/scenes-sdk7/interactividad/avatares/move-player.md).

# Mover al jugador

Teletransporta al jugador, o haz que camine hasta una nueva posición dentro de tu escena

Para cambiar la posición del jugador en la escena, usa la `movePlayerTo()` función. Úsala para reaparecer a los jugadores, configurar puntos de control o hacer que un jugador camine hasta un lugar como parte de una cinemática.

{% hint style="info" %}
**💡 Consejo**: La forma más sencilla de mover al jugador es usar el [Scene Editor en Creator Hub](https://docs.decentraland.org/creator/content-creator-es/scene-editor/primeros-pasos/about-editor.md). Usa las acciones sin código **Move player** o **Move player here** ; consulta [Make any item smart](https://docs.decentraland.org/creator/content-creator-es/scene-editor/interactividad/make-any-item-smart.md).
{% endhint %}

Esta función recibe un objeto con las siguientes propiedades:

* `newRelativePosition`: Dónde posicionar al jugador, expresado como un Vector3.
* `cameraTarget`: (opcional) La dirección hacia la que debe apuntar la cámara, expresada como un Vector3 que representa las coordenadas de un punto en el espacio al que mirar. Si no se proporciona ningún valor, la cámara conservará la misma rotación que tenía antes del movimiento.
* `avatarTarget`: (opcional) La dirección hacia la que debe apuntar el Avatar, expresada como un Vector3 que representa las coordenadas de un punto en el espacio al que mirar. Si no se proporciona ningún valor, el Avatar conservará la misma rotación que tenía antes del movimiento. Si el jugador está en el modo de cámara en primera persona, la rotación de la cámara y la del Avatar son iguales.
* `duration`: (opcional) Cuánto debe durar la transición, en segundos. Si no se proporciona ningún valor, la transición será instantánea. Si se proporciona una duración, el Avatar caminará o correrá hasta esta nueva posición.

{% hint style="warning" %}
**📔 Nota**: Durante la transición, los colliders no afectan al Avatar, por lo que puede atravesar objetos.
{% endhint %}

```ts
import { movePlayerTo } from '~system/RestrictedActions'

// crear entidad
const myEntity = engine.addEntity()
MeshRenderer.setBox(myEntity)
MeshCollider.setBox(myEntity)

Transform.create(myEntity, {
	position: { x: 4, y: 1, z: 4 },
})

// asignar comportamiento a la entidad
pointerEventsSystem.onPointerDown(
	{
		entity: myEntity,
		opts: { button: InputAction.IA_POINTER, hoverText: 'Click' },
	},
	function () {
		// hacer reaparecer al jugador
		movePlayerTo({
			newRelativePosition: Vector3.create(1, 0, 1),
			cameraTarget: Vector3.create(8, 1, 8),
			avatarTarget: Vector3.create(8, 1, 8),
		})
	}
)
```

El jugador se mueve instantáneamente, sin pantallas de confirmación ni transiciones de cámara.

{% hint style="warning" %}
**📔 Nota**: Los jugadores solo pueden moverse si ya están dentro de los límites de la escena, y solo pueden trasladarse a ubicaciones que estén dentro de esos límites. No puedes usar `movePlayerTo()` para transportar a un jugador a otra escena. Para mover a un jugador a otra escena, consulta [Teleports](https://docs.decentraland.org/creator/content-creator-es/scenes-sdk7/interactividad/external-links.md#teleports).
{% endhint %}

La `movePlayerTo()` función admite await, por lo que, si el movimiento tiene una duración, puedes usar `await` para esperar a que el jugador llegue a su destino.

```ts
import { movePlayerTo } from '~system/RestrictedActions'

pointerEventsSystem.onPointerDown(
	{
		entity: myEntity,
		opts: { button: InputAction.IA_POINTER, hoverText: 'Click' },
	},
	async function () {
		await movePlayerTo({
			newRelativePosition: Vector3.create(1, 0, 1),
			cameraTarget: Vector3.create(8, 1, 8),
			avatarTarget: Vector3.create(8, 1, 8),
			duration: 2,
		})
	}
)
```

{% hint style="warning" %}
**📔 Nota**: Sin un `duration`, la promesa se resuelve en cuanto se pone en cola el teletransporte, no cuando el jugador ha llegado. El código después de `await` se ejecuta mientras `Transform.get(engine.PlayerEntity)` sigue indicando la posición anterior, y el movimiento que lo lleva al destino un momento después puede interrumpir un Emote que hayas iniciado allí. Si es necesario que algo ocurra al llegar, consulta la posición del jugador periódicamente:

```ts
import { engine, Transform } from '@dcl/sdk/ecs'
import { Vector3 } from '@dcl/sdk/math'
import { movePlayerTo } from '~system/RestrictedActions'

function teleportThen(target: Vector3, onArrive: () => void) {
	void movePlayerTo({ newRelativePosition: target })

	let waited = 0
	function waitForArrival(dt: number) {
		waited += dt
		const pos = Transform.getOrNull(engine.PlayerEntity)?.position
		// comparar solo X y Z para que una diferencia de altura no detenga la espera
		const arrived = pos !== undefined && Math.hypot(pos.x - target.x, pos.z - target.z) < 0.2
		if (!arrived && waited < 1.5) return // abandonar después de 1.5 s
		engine.removeSystem(waitForArrival)
		onArrive()
	}

	engine.addSystem(waitForArrival)
}
```

{% endhint %}

Si el jugador intenta moverse durante la duración de la transición, esta se interrumpirá y la función `movePlayerTo` nunca se resolverá. Puedes evitar este comportamiento desactivando todas las entradas mientras la transición está en curso mediante el componente `InputModifier` , consulta [Restringir el movimiento](https://docs.decentraland.org/creator/content-creator-es/scenes-sdk7/interactividad/avatares/locomotion.md#restrict-locomotion).

```ts
import { movePlayerTo } from '~system/RestrictedActions'
import {InputModifier, engine} from '@dcl/sdk/ecs'

pointerEventsSystem.onPointerDown(
	{
		entity: myEntity,
		opts: { button: InputAction.IA_POINTER, hoverText: 'Click' },
	},
	async function () {

		// desactivar todas las entradas
		InputModifier.create(engine.PlayerEntity, {
			mode: InputModifier.Mode.Standard({
				disableAll: true,
			}),
		})

		// mover al jugador
		await movePlayerTo({
			newRelativePosition: Vector3.create(1, 0, 1),
			cameraTarget: Vector3.create(8, 1, 8),
			avatarTarget: Vector3.create(8, 1, 8),
			duration: 2,
		})

		// activar todas las entradas
		InputModifier.deleteFrom(engine.PlayerEntity)
	}
)
```

{% hint style="warning" %}
**📔 Nota**: Además, el resultado de await se puede almacenar para evaluar su propiedad `success` y saber si el movimiento se interrumpió (por ejemplo, por el movimiento del jugador) o si se completó correctamente.
{% endhint %}

{% hint style="info" %}
**💡 Consejo**: Para mover a un jugador a otra Scene o a otras coordenadas del mapa de Genesis City, consulta [Teletransportes](https://docs.decentraland.org/creator/content-creator-es/scenes-sdk7/interactividad/external-links.md#teleports).
{% endhint %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.decentraland.org/creator/content-creator-es/scenes-sdk7/interactividad/avatares/move-player.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
