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);
}
I'd also like to add a tag to all the objects, so every cube that has that tag would be teleported to if the camera clicks on it.
Answer by Geometrical · Mar 26, 2016 at 11:19 PM
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.
CameraTeleport.cs
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 = Vector3.zero;
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;
}
}
}
}
}
Answer by Vallar · Mar 26, 2016 at 07:57 PM
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.
Hi, thank you, but I since there are several cubes, is there a way to move the position to the cube I'm clicking on, so if there are 3 cubes, and I click one the camera moves to that cube. I tried to do it with tags but I can't find the solution
Your answer
![](https://koobas.hobune.stream/wayback/20220612073406im_/https://answers.unity.com/themes/thub/images/avi.jpg)