> 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-pt/scenes-sdk7/interatividade/avatares/move-player.md).

# Mover o Player

Teleportar o jogador, ou fazê-lo andar até uma nova posição dentro da sua scene

Para alterar a posição do jogador na cena, use a `movePlayerTo()` função. Use-a para fazer ressurgir jogadores, configurar pontos de controlo ou fazer um jogador caminhar até um local como parte de uma cena cinematográfica.

{% hint style="info" %}
**💡 Dica**: A forma mais fácil de mover o jogador é utilizar o [Scene Editor no Creator Hub](https://docs.decentraland.org/creator/content-creator-pt/scene-editor/primeiros-passos/about-editor.md). Utilize a ação sem código **Move player** ou a ação **Move player here** ; consulte [Tornar qualquer item inteligente](https://docs.decentraland.org/creator/content-creator-pt/scene-editor/interatividade/make-any-item-smart.md).
{% endhint %}

Esta função recebe um objeto com as seguintes propriedades:

* `newRelativePosition`: Onde posicionar o jogador, expresso como um Vector3.
* `cameraTarget`: (opcional) A direção para a qual a câmara deve apontar, expressa como um Vector3 que representa as coordenadas de um ponto no espaço para onde olhar. Se não for fornecido nenhum valor, a câmara mantém a mesma rotação que tinha antes do movimento.
* `avatarTarget`: (opcional) A direção para a qual o Avatar deve estar virado, expressa como um Vector3 que representa as coordenadas de um ponto no espaço para onde olhar. Se não for fornecido nenhum valor, o Avatar mantém a mesma rotação que tinha antes do movimento. Se o jogador estiver no modo de câmara em primeira pessoa, a rotação da câmara e do Avatar é a mesma.
* `duration`: (opcional) A duração da transição, em segundos. Se não for fornecido nenhum valor, a transição ocorre instantaneamente. Se for indicada uma duração, o Avatar caminha ou corre até esta nova posição.

{% hint style="warning" %}
**📔 Nota**: Durante a transição, o Avatar não é afetado pelos Colliders, pelo que pode atravessar objetos.
{% endhint %}

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

// criar entidade
const myEntity = engine.addEntity()
MeshRenderer.setBox(myEntity)
MeshCollider.setBox(myEntity)

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

// give entity behavior
pointerEventsSystem.onPointerDown(
	{
		entity: myEntity,
		opts: { button: InputAction.IA_POINTER, hoverText: 'Click' },
	},
	function () {
		// respawn player
		movePlayerTo({
			newRelativePosition: Vector3.create(1, 0, 1),
			cameraTarget: Vector3.create(8, 1, 8),
			avatarTarget: Vector3.create(8, 1, 8),
		})
	}
)
```

O movimento do jogador ocorre instantaneamente, sem ecrãs de confirmação nem transições de câmara.

{% hint style="warning" %}
**📔 Nota**: Os jogadores só podem ser movidos se já estiverem dentro dos limites da cena e só podem ser movidos para locais dentro desses limites. Não pode utilizar `movePlayerTo()` para transportar um jogador para outra cena. Para mover um jogador para outra cena, consulte [Teleports](https://docs.decentraland.org/creator/content-creator-pt/scenes-sdk7/interatividade/external-links.md#teleports).
{% endhint %}

A função `movePlayerTo()` pode ser aguardada com await; assim, se o movimento tiver uma duração, pode utilizar `await` para aguardar que o jogador chegue ao 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**: Sem um valor para `duration`, a Promise é resolvida assim que o teletransporte é colocado na fila, e não quando o jogador chega. O código após `await` é executado enquanto `Transform.get(engine.PlayerEntity)` continua a indicar a posição antiga, e o movimento que ocorre um instante depois pode interromper um Emote iniciado nesse local. Se algo tiver de acontecer à chegada, consulte a posição do jogador periodicamente:

```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 apenas X e Z, para que uma diferença de altura não prolongue a espera indefinidamente
		const arrived = pos !== undefined && Math.hypot(pos.x - target.x, pos.z - target.z) < 0.2
		if (!arrived && waited < 1.5) return // desistir após 1,5 s
		engine.removeSystem(waitForArrival)
		onArrive()
	}

	engine.addSystem(waitForArrival)
}
```

{% endhint %}

Se o jogador tentar mover-se durante a transição, esta será interrompida e a `movePlayerTo` function nunca será resolvida. Pode evitar este comportamento desativando todos os controlos enquanto a transição está em curso, utilizando o componente `InputModifier` , consulte [Restringir a locomoção](https://docs.decentraland.org/creator/content-creator-pt/scenes-sdk7/interatividade/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 () {

		// desativar todos os controlos
		InputModifier.create(engine.PlayerEntity, {
			mode: InputModifier.Mode.Standard({
				disableAll: true,
			}),
		})

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

		// ativar todos os controlos
		InputModifier.deleteFrom(engine.PlayerEntity)
	}
)
```

{% hint style="warning" %}
**📔 Nota**: Além disso, o resultado de await pode ser guardado para verificar a propriedade `success` e saber se o movimento foi interrompido (por exemplo, por movimento introduzido pelo utilizador) ou concluído com sucesso.
{% endhint %}

{% hint style="info" %}
**💡 Dica**: Para mover um jogador para outra Scene ou para coordenadas diferentes no mapa de Genesis City, consulte [Teletransportes](https://docs.decentraland.org/creator/content-creator-pt/scenes-sdk7/interatividade/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-pt/scenes-sdk7/interatividade/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.
