Teleport camera to where is pointing at

Hi, so I have attached an event trigger to a cube and I want my camera to teleport to where the cube is currently at,

so far I just created this method, it works fine but if the cube moves or if I want to add another cube, I would have to adjust the coordinates manually, is there a way to just use the coordinates from an object and stablish them as the new position of my camera?

	public void MoveUp()

		transform.position += new Vector3 (6f, 2f, 1f);

If I understand correctly, you want to set the position of the camera to the cube, right?

In that case, in your camera, add a script that looks like this for example:

using UnityEngine;
using System.Collections;

public class CamerMovement: MonoBehaviour

   public GameObject cube;

   void Update()
         transform.position = cube.transform.position;

That should set the position of the camera to the exact position of the cube every frame. So if the cube moved, the camera will move to its location.

Hope that helps.

Just quickly wrote up a script to do exactly what you need out of sheer courtesy. All you need to do is change the tag on the cubes you wish the camera to teleport to.


using UnityEngine;
using System.Collections;

public class CameraTeleport : MonoBehaviour {

	// The tag of the cubes you want to teleport to
	public string cameraTeleportTag = "TeleportCube";

	// The offset to apply to the centre of the cube when teleporting for fine tuning
	public Vector3 teleportOffset =;

	private void Update () {
		// Check if the left mouse button is being pressed
		if (Input.GetMouseButtonDown (0)) {
			// Stores collision information
			RaycastHit raycastHit;

			// Create a ray from screen coordinates of the mouse into the world space
			Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);

			// Cast our ray and see if it hits anything
			if (Physics.Raycast (ray.origin, ray.direction, out raycastHit, float.PositiveInfinity)) {

				// The gameobject we hit
				GameObject raycastHitTarget = raycastHit.collider.gameObject;

				// Check if we hit a cube to teleport to by its tag
				if (raycastHitTarget.tag == cameraTeleportTag) {

					// Teleport the cube
					transform.position = raycastHit.transform.position;