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);
}
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;
}
}
}
}
}